1use std::collections::{BTreeMap, BTreeSet, VecDeque};
14use std::fs::File;
15
16use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
17use nibkeep_crypto::VerifyingKey;
18use nibkeep_crypto::rand_core::CryptoRng;
19use nibkeep_log::list::MEMBERSHIP;
20use nibkeep_model::storage::Statements as _;
21use nibkeep_model::{FieldName, Operation, Statement, TypeName, Value, fields};
22use nibkeep_std::{
23 ATTACHED_TO, CHECKED_OUT_ON, CHECKOUT_OF, CONTENT, FILE, FOUND_ON, IN_FOLDER, IN_TREE,
24 ORIGIN_OF, THUMBNAIL, THUMBNAIL_OF,
25};
26use nibkeep_time::Timestamp;
27
28use super::export::OWN_RECORDS;
29use super::links::Links;
30use super::{Library, held_copies_in};
31use crate::NodeError;
32
33const MOST_MOVES: usize = 16;
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum MoveHistory {
41 Bring,
44 Leave,
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum Behind {
53 Purge,
56 Keep,
58}
59
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum MoveSecrets {
66 Bring,
70 Leave,
73}
74
75#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct MovePreview {
78 pub entities: Vec<EntityId>,
81 pub staying: Vec<EntityId>,
84 pub losing: Vec<String>,
87 pub gaining: Vec<String>,
90 pub purges_all: bool,
94 pub secrets: bool,
100}
101
102struct Carried {
104 statement: Statement,
105 secret: bool,
108 recorded: Option<Timestamp>,
110 author: Option<VerifyingKey>,
112 replaced: Option<Timestamp>,
114}
115
116struct Taken {
120 entities: Vec<(EntityId, Vec<Carried>)>,
121 copies: Vec<(EntityId, Vec<Carried>)>,
124 contents: BTreeMap<Hash, (BTreeSet<FieldName>, bool)>,
125 kinds: BTreeSet<TypeName>,
126 secret: BTreeSet<FieldName>,
127}
128
129impl Taken {
130 fn copy(&mut self, entity: EntityId, carried: Vec<Carried>) {
133 self.add(entity, carried);
134 if let Some(copied) = self.entities.pop() {
135 self.copies.push(copied);
136 }
137 }
138
139 fn add(&mut self, entity: EntityId, carried: Vec<Carried>) {
142 for statement in &carried {
143 if statement.secret {
144 self.secret.insert(statement.statement.field.clone());
145 }
146 if let Value::Blob(content) = statement.statement.value
147 && !nibkeep_std::names_content_only(&statement.statement.field)
148 {
149 let (holding, now) = self.contents.entry(content).or_default();
150 holding.insert(statement.statement.field.clone());
151 *now |= statement.replaced.is_none();
152 }
153 }
154 self.entities.push((entity, carried));
155 }
156}
157
158impl Library {
159 #[expect(
189 clippy::too_many_arguments,
190 reason = "one move, with the choices the person makes"
191 )]
192 pub fn move_entity(
193 &mut self,
194 from: SpaceId,
195 entity: EntityId,
196 to: SpaceId,
197 history: MoveHistory,
198 behind: Behind,
199 secrets: MoveSecrets,
200 wall_millis: u64,
201 rng: &mut impl CryptoRng,
202 ) -> Result<EntityId, NodeError> {
203 self.check_move(from, to)?;
204 self.check_not_group(to)?;
205 self.catch_up()?;
207 let taken = self.to_move((from, to), entity, (history, secrets))?;
208 self.check_contents_here((from, to), &taken)?;
210 self.prepare_secrets((from, to), &taken, wall_millis, rng)?;
211 let source_types = self.types(from)?;
214 for kind in &taken.kinds {
215 if let Some(definition) = source_types.get(kind) {
216 let careful = self.space(to)?.types.careful(definition);
217 self.define_type(to, &careful, wall_millis, rng)?;
218 }
219 }
220 self.keep_secret(to, &taken.secret, wall_millis, rng)?;
222 let secret_there = self.space(to)?.stored.secret_fields().clone();
226 for (content, (holding, now)) in &taken.contents {
227 if !now && !self.space(from)?.stored.holds_blob(content) {
228 continue;
229 }
230 let kinds: BTreeSet<bool> = holding
231 .iter()
232 .map(|field| secret_there.contains(field))
233 .collect();
234 for secret in kinds {
235 self.copy_blob(from, content, (to, secret), wall_millis, rng)?;
236 }
237 }
238 let new: BTreeMap<EntityId, EntityId> = taken
239 .entities
240 .iter()
241 .chain(&taken.copies)
242 .map(|(old, _)| (*old, EntityId::random(rng)))
243 .collect();
244 let mut marks = Vec::new();
245 for (old, _) in &taken.entities {
246 marks.push(Operation::assert(Statement::new(
247 StatementId::random(rng),
248 *old,
249 fields::MOVED_INTO,
250 Value::Reference(new[old]),
251 )));
252 if behind == Behind::Purge {
255 marks.push(Operation::assert(Statement::new(
256 StatementId::random(rng),
257 *old,
258 fields::PURGE_ASKED,
259 Value::Boolean(true),
260 )));
261 } else {
262 let asked: Vec<StatementId> = self
263 .space(from)?
264 .stored
265 .log()
266 .state()
267 .current(*old, &fields::PURGE_ASKED)?
268 .iter()
269 .map(|statement| statement.id)
270 .collect();
271 if !asked.is_empty() {
272 marks.push(Operation::retract(*old, asked));
273 }
274 }
275 }
276 self.commit(from, marks, wall_millis, rng)?;
277 let mut operations = Vec::new();
278 for (old, carried) in taken.entities.iter().chain(&taken.copies) {
279 operations.extend(carried_operations(
280 carried,
281 (new[old], &new),
282 (from, history),
283 rng,
284 ));
285 }
286 self.commit(to, operations, wall_millis, rng)?;
287 let given = taken.entities.first().map_or(entity, |(old, _)| *old);
288 Ok(new[&given])
289 }
290
291 pub fn move_preview(
303 &self,
304 from: SpaceId,
305 entity: EntityId,
306 to: SpaceId,
307 ) -> Result<MovePreview, NodeError> {
308 self.check_move(from, to)?;
309 self.space(from)?.stored.reading(|_| {
310 let entities = self.held_with(from, entity)?;
311 for &each in &entities {
312 self.check_movable(from, each)?;
313 }
314 let staying = self.staying_holders(from, &entities)?;
315 let (losing, purges_all) = self.losing_and_purging((from, to))?;
316 let (gaining, _) = self.losing_and_purging((to, from))?;
317 let state = self.space(from)?.stored.log().state();
319 let mut kinds = BTreeSet::new();
320 for &each in &entities {
321 kinds.extend(state.types(each)?);
322 }
323 let secret_there = self.secret_once_moved((from, to), &kinds)?;
324 let mut secrets = false;
325 for &each in &entities {
326 secrets |= self.may_hold_secrets(from, each)?;
327 for member in state.merged(each)? {
328 secrets |= state
329 .storage()
330 .of_entity(member)?
331 .iter()
332 .any(|(field, _)| secret_there.contains(field));
333 }
334 }
335 Ok(MovePreview {
336 entities,
337 staying,
338 losing,
339 gaining,
340 purges_all,
341 secrets,
342 })
343 })
344 }
345
346 fn check_move(&self, from: SpaceId, to: SpaceId) -> Result<(), NodeError> {
349 if from == to {
350 return Err(NodeError::SameSpace);
351 }
352 self.space(from)?;
353 self.space(to)?;
354 self.check_not_ai_agent("move entities")?;
355 self.check_not_revoked(from)?;
356 self.check_not_revoked(to)
357 }
358
359 pub fn moved_into(
368 &self,
369 space: SpaceId,
370 entity: EntityId,
371 ) -> Result<Option<(SpaceId, EntityId)>, NodeError> {
372 let mut at = (space, entity);
373 let mut found = None;
374 for _ in 0..MOST_MOVES {
375 let Some(next) = self.moved_once(at.0, at.1)? else {
376 break;
377 };
378 if next == (space, entity) || found == Some(next) {
379 break;
380 }
381 found = Some(next);
382 at = next;
383 }
384 Ok(found)
385 }
386
387 pub fn moved_from(
395 &self,
396 space: SpaceId,
397 entity: EntityId,
398 ) -> Result<Vec<(SpaceId, EntityId)>, NodeError> {
399 let state = self.space(space)?.stored.log().state();
400 let canonical = state.canonical(entity)?;
401 let mut found: Vec<(SpaceId, EntityId)> = Vec::new();
402 let mut reached: Vec<(SpaceId, EntityId)> = state
403 .merged(canonical)?
404 .into_iter()
405 .map(|member| (space, member))
406 .collect();
407 for _ in 0..MOST_MOVES {
408 let mut next = Vec::new();
409 for &(into, moved) in &reached {
410 for held in self.spaces() {
411 if held == into {
412 continue;
413 }
414 let marked = self
415 .space(held)?
416 .stored
417 .find(&fields::MOVED_INTO, &Value::Reference(moved))?;
418 for old in marked {
419 if held != space && !found.contains(&(held, old)) {
420 found.push((held, old));
421 next.push((held, old));
422 }
423 }
424 }
425 }
426 if next.is_empty() {
427 break;
428 }
429 reached = next;
430 }
431 let mut leading = Vec::new();
432 for (held, old) in found {
433 if let Some((there, now)) = self.moved_into(held, old)?
434 && there == space
435 && state.canonical(now)? == canonical
436 {
437 leading.push((held, old));
438 }
439 }
440 Ok(leading)
441 }
442
443 pub fn links_to_anywhere(
456 &self,
457 space: SpaceId,
458 entity: EntityId,
459 day: nibkeep_time::Day,
460 limit: usize,
461 ) -> Result<Vec<Links>, NodeError> {
462 let moved_from = self.moved_from(space, entity)?;
463 if moved_from.is_empty() {
464 return self.links_to(space, entity, day, limit);
465 }
466 let mut links = self.links_to(space, entity, day, usize::MAX)?;
467 let here: BTreeSet<EntityId> = links
468 .iter()
469 .flat_map(|links| links.entities.iter().map(|linking| linking.id))
470 .collect();
471 for (held, old) in moved_from {
472 for mut other in self.links_to(held, old, day, usize::MAX)? {
473 let mut kept = Vec::new();
474 for linking in other.entities {
475 let linked_here = self
476 .moved_into(held, linking.id)?
477 .is_some_and(|(there, now)| there == space && here.contains(&now));
478 if !linked_here {
479 kept.push(linking);
480 }
481 }
482 if kept.is_empty() {
483 continue;
484 }
485 other.count = kept.len();
486 other.entities = kept;
487 match links.iter_mut().find(|links| links.field == other.field) {
488 Some(same) => {
489 same.count += other.count;
490 same.entities.extend(other.entities);
491 }
492 None => links.push(other),
493 }
494 }
495 }
496 for group in &mut links {
497 group.entities.sort_by_key(|linking| {
498 (
499 linking.name.is_none(),
500 linking.name.as_deref().map(str::to_lowercase),
501 linking.id,
502 )
503 });
504 group.entities.truncate(limit);
505 }
506 Ok(links)
507 }
508
509 fn moved_once(
512 &self,
513 space: SpaceId,
514 entity: EntityId,
515 ) -> Result<Option<(SpaceId, EntityId)>, NodeError> {
516 let state = self.space(space)?.stored.log().state();
517 let mut targets: Vec<EntityId> = state
518 .current(entity, &fields::MOVED_INTO)?
519 .iter()
520 .filter_map(|statement| statement.value.as_reference())
521 .collect();
522 targets.sort();
523 for target in targets {
524 for held in self.spaces() {
525 if held == space {
526 continue;
527 }
528 let there = self.space(held)?.stored.log().state();
529 if !there.fields(target)?.is_empty() {
530 return Ok(Some((held, target)));
531 }
532 }
533 }
534 Ok(None)
535 }
536
537 pub fn name_anywhere(&self, entity: EntityId) -> Result<Option<String>, NodeError> {
544 let Some(space) = self.space_of(entity)? else {
545 return Ok(None);
546 };
547 match self.moved_into(space, entity)? {
548 Some((there, moved)) => self.name(there, moved),
549 None => self.name(space, entity),
550 }
551 }
552
553 fn to_move(
556 &self,
557 (from, to): (SpaceId, SpaceId),
558 entity: EntityId,
559 (history, secrets): (MoveHistory, MoveSecrets),
560 ) -> Result<Taken, NodeError> {
561 self.space(from)?.stored.reading(|_| {
562 let held = self.held_with(from, entity)?;
563 let moving: BTreeSet<EntityId> = held.iter().copied().collect();
564 let mut taken = Taken {
565 entities: Vec::new(),
566 copies: Vec::new(),
567 contents: BTreeMap::new(),
568 kinds: BTreeSet::new(),
569 secret: BTreeSet::new(),
570 };
571 for each in held {
572 taken.kinds.extend(self.check_movable(from, each)?);
573 if secrets == MoveSecrets::Bring
575 && !self.secrets_unlocked(from)
576 && self.may_hold_secrets(from, each)?
577 {
578 return Err(NodeError::MoveNeedsSecrets);
579 }
580 let carried = self.carried_of((from, to), each, (history, secrets), &moving)?;
581 taken.add(each, carried);
582 }
583 for (thumbnail, copied) in self.thumbnails_moving((from, &moving), &taken)? {
587 taken.kinds.extend(self.check_movable(from, thumbnail)?);
588 let carried =
589 self.carried_of((from, to), thumbnail, (history, secrets), &moving)?;
590 if copied {
591 taken.copy(thumbnail, carried);
592 } else {
593 taken.add(thumbnail, carried);
594 }
595 }
596 for record in self.plain_copies_moving((from, to), &moving, &taken)? {
602 taken.kinds.extend(self.check_movable(from, record)?);
603 let carried = self.carried_of((from, to), record, (history, secrets), &moving)?;
604 taken.add(record, carried);
605 }
606 Ok(taken)
607 })
608 }
609
610 fn plain_copies_moving(
619 &self,
620 (from, to): (SpaceId, SpaceId),
621 moving: &BTreeSet<EntityId>,
622 taken: &Taken,
623 ) -> Result<Vec<EntityId>, NodeError> {
624 let personal = self.space(self.info.personal)?.stored.log().state();
625 let devices = self.holding_devices(to)?;
626 let open = self.space(from)?;
627 let state = open.stored.log().state();
628 let mut files = BTreeSet::new();
629 for &each in moving {
630 files.extend(state.merged(each)?);
631 }
632 let mut moving_along = Vec::new();
633 for (record, moved, deleted) in self.plain_copies_of(from, &files)? {
634 if moved || deleted {
635 continue;
636 }
637 let device = state
638 .current(record, &FOUND_ON)?
639 .into_iter()
640 .chain(state.current(record, &CHECKED_OUT_ON)?)
641 .find_map(|statement| statement.value.as_reference());
642 let Some(device) = device else {
643 continue;
644 };
645 let content = state
646 .current(record, &CONTENT)?
647 .into_iter()
648 .find_map(|statement| match statement.value {
649 Value::Blob(content) => Some(content),
650 _ => None,
651 });
652 if devices.contains(&personal.canonical(device)?)
653 && content.is_none_or(|content| taken.contents.contains_key(&content))
654 {
655 moving_along.push(record);
656 }
657 }
658 Ok(moving_along)
659 }
660
661 pub(crate) fn plain_copies_of(
665 &self,
666 space: SpaceId,
667 entities: &BTreeSet<EntityId>,
668 ) -> Result<Vec<(EntityId, bool, bool)>, NodeError> {
669 let open = self.space(space)?;
670 let state = open.stored.log().state();
671 let mut found = BTreeMap::new();
672 for &entity in entities {
673 for field in [&ORIGIN_OF, &CHECKOUT_OF] {
674 for statement in state.referrers_in(entity, field)? {
675 let record = state.canonical(statement.entity)?;
676 if entities.contains(&record) {
677 continue;
678 }
679 let moved = !state.current(record, &fields::MOVED_INTO)?.is_empty();
680 found.insert(record, (moved, state.is_deleted(record)?));
681 }
682 }
683 }
684 Ok(found
685 .into_iter()
686 .map(|(record, (moved, deleted))| (record, moved, deleted))
687 .collect())
688 }
689
690 fn thumbnails_moving(
696 &self,
697 (from, moving): (SpaceId, &BTreeSet<EntityId>),
698 taken: &Taken,
699 ) -> Result<Vec<(EntityId, bool)>, NodeError> {
700 let open = self.space(from)?;
701 let state = open.stored.log().state();
702 let gone =
703 |entity: EntityId| -> Result<bool, NodeError> {
704 Ok(state.is_deleted(entity)?
705 || !state.current(entity, &fields::MOVED_INTO)?.is_empty())
706 };
707 let mut thumbnails = BTreeMap::new();
708 for (content, (holding, _)) in &taken.contents {
709 if !holding.contains(&CONTENT) || open.stored.secret_fields().contains(&CONTENT) {
710 continue;
711 }
712 let mut staying = false;
713 for file in open.stored.find(&CONTENT, &Value::Blob(*content))? {
714 let file = state.canonical(file)?;
715 staying |=
716 !moving.contains(&file) && state.types(file)?.contains(&FILE) && !gone(file)?;
717 }
718 for thumbnail in open.stored.find(&THUMBNAIL_OF, &Value::Blob(*content))? {
719 let thumbnail = state.canonical(thumbnail)?;
720 if !moving.contains(&thumbnail)
721 && state.types(thumbnail)?.contains(&THUMBNAIL)
722 && !gone(thumbnail)?
723 {
724 *thumbnails.entry(thumbnail).or_insert(false) |= staying;
725 }
726 }
727 }
728 Ok(thumbnails.into_iter().collect())
729 }
730
731 pub fn may_hold_secrets(&self, space: SpaceId, entity: EntityId) -> Result<bool, NodeError> {
740 let open = self.space(space)?;
741 let state = open.stored.log().state();
742 let storage = state.storage();
743 let secret = open.stored.secret_fields();
744 for member in state.merged(entity)? {
745 for (field, ids) in storage.of_entity(member)? {
746 if secret.contains(&field) {
747 return Ok(true);
748 }
749 for id in ids {
750 if storage.is_secret(id)? {
751 return Ok(true);
752 }
753 }
754 }
755 }
756 if self.secrets_unlocked(space) {
757 return Ok(false);
758 }
759 let kinds: Vec<TypeName> = state.types(entity)?.into_iter().collect();
760 Ok(!self.secret_fields_of(space, &kinds)?.is_empty())
761 }
762
763 fn secret_once_moved(
767 &self,
768 (from, to): (SpaceId, SpaceId),
769 kinds: &BTreeSet<TypeName>,
770 ) -> Result<BTreeSet<FieldName>, NodeError> {
771 let mut secret_there = self.space(to)?.stored.secret_fields().clone();
772 let source_types = &self.space(from)?.types;
773 for kind in kinds {
774 if let Some(definition) = source_types.get(kind) {
775 secret_there.extend(
776 definition
777 .fields()
778 .filter(|(_, field)| field.is_secret())
779 .map(|(name, _)| name.clone()),
780 );
781 }
782 }
783 Ok(secret_there)
784 }
785
786 fn check_contents_here(
789 &self,
790 (from, to): (SpaceId, SpaceId),
791 taken: &Taken,
792 ) -> Result<(), NodeError> {
793 let (source, target) = (&self.space(from)?.stored, &self.space(to)?.stored);
794 for (content, (_, now)) in &taken.contents {
795 if *now
796 && !source.holds_blob(content)
797 && !target.holds_blob(content)
798 && self.originals_here(from, content)?.is_empty()
799 {
800 return Err(NodeError::NotHere(content.to_string()));
801 }
802 }
803 Ok(())
804 }
805
806 fn prepare_secrets(
812 &mut self,
813 (from, to): (SpaceId, SpaceId),
814 taken: &Taken,
815 wall_millis: u64,
816 rng: &mut impl CryptoRng,
817 ) -> Result<(), NodeError> {
818 let secret_there = self.secret_once_moved((from, to), &taken.kinds)?;
819 if let Some(field) = taken.secret.difference(&secret_there).next()
820 && !self.may_mark_secret(to)?
821 {
822 return Err(NodeError::NotSecretThere(field.clone()));
823 }
824 let sealed_there = taken.entities.iter().any(|(_, carried)| {
825 carried.iter().any(|statement| {
826 let field = &statement.statement.field;
827 secret_there.contains(field) || taken.secret.contains(field)
828 })
829 });
830 if !sealed_there || self.secrets_unlocked(to) {
831 return Ok(());
832 }
833 if to == self.info.personal {
834 return Err(NodeError::MoveNeedsSecrets);
835 }
836 self.set_up_space_secrets(to, wall_millis, rng)
837 }
838
839 fn may_mark_secret(&self, space: SpaceId) -> Result<bool, NodeError> {
842 Ok(space == self.info.personal
843 || !self.has_members(space)?
844 || self.check_admin(space, "make a field secret").is_ok())
845 }
846
847 fn keep_secret(
850 &mut self,
851 to: SpaceId,
852 secret: &BTreeSet<FieldName>,
853 wall_millis: u64,
854 rng: &mut impl CryptoRng,
855 ) -> Result<(), NodeError> {
856 let open = self.space(to)?;
857 let missing: Vec<FieldName> = secret
858 .difference(open.stored.secret_fields())
859 .cloned()
860 .collect();
861 let Some(first) = missing.first().cloned() else {
862 return Ok(());
863 };
864 if !self.may_mark_secret(to)? {
865 return Err(NodeError::NotSecretThere(first));
866 }
867 let own = self.own_record(to)?;
868 let operations = open.secret_marks(&self.code_types, (own, missing), rng)?;
869 if operations.is_empty() {
870 return Err(NodeError::NotSecretThere(first));
871 }
872 self.commit(to, operations, wall_millis, rng)?;
873 self.read_again(to)?;
875 if self.space(to)?.stored.secret_fields().contains(&first) {
876 Ok(())
877 } else {
878 Err(NodeError::NotSecretThere(first))
879 }
880 }
881
882 fn held_with(&self, from: SpaceId, entity: EntityId) -> Result<Vec<EntityId>, NodeError> {
888 let open = self.space(from)?;
889 let state = open.stored.log().state();
890 let given = state.canonical(entity)?;
891 if state.fields(given)?.is_empty() || state.is_deleted(given)? {
892 return Err(NodeError::NoEntity(given.to_string()));
893 }
894 if state.types(given)?.contains(&MEMBERSHIP) {
895 return Err(NodeError::OwnRecord(given.to_string()));
896 }
897 if self.moved_into(from, given)?.is_some() {
898 return Err(NodeError::MovedAlready);
899 }
900 let naming = |field: &FieldName, each: EntityId| -> Result<Vec<EntityId>, NodeError> {
901 let mut found = Vec::new();
902 for member in state.merged(each)? {
903 found.extend(open.stored.find(field, &Value::Reference(member))?);
904 }
905 Ok(found)
906 };
907 let mut held = Vec::new();
908 let mut seen = BTreeSet::new();
909 let mut waiting = VecDeque::from([given]);
910 while let Some(next) = waiting.pop_front() {
911 let each = state.canonical(next)?;
912 if !seen.insert(each) {
913 continue;
914 }
915 if each != given
916 && (state.fields(each)?.is_empty()
917 || state.is_deleted(each)?
918 || self.moved_into(from, each)?.is_some())
919 {
920 continue;
921 }
922 if state.fields(each)?.contains(&IN_TREE) || !naming(&IN_TREE, each)?.is_empty() {
923 return Err(NodeError::TreeStays(each.to_string()));
924 }
925 held.push(each);
926 waiting.extend(naming(&IN_FOLDER, each)?);
927 for file in naming(&ATTACHED_TO, each)? {
930 let file = state.canonical(file)?;
931 let mut alone = true;
932 for statement in state.current(file, &ATTACHED_TO)? {
933 let Some(other) = statement.value.as_reference() else {
934 continue;
935 };
936 let other = state.canonical(other)?;
937 if other != each
938 && !held.contains(&other)
939 && !waiting.contains(&other)
940 && !state.fields(other)?.is_empty()
941 && !state.is_deleted(other)?
942 && self.moved_into(from, other)?.is_none()
943 {
944 alone = false;
945 break;
946 }
947 }
948 if alone {
949 waiting.push_back(file);
950 }
951 }
952 for membership in naming(&fields::LIST, each)? {
953 let membership = state.canonical(membership)?;
954 if !state.types(membership)?.contains(&MEMBERSHIP)
955 || state.is_deleted(membership)?
956 {
957 continue;
958 }
959 waiting.push_back(membership);
960 waiting.extend(
961 state
962 .current(membership, &fields::ITEM)?
963 .iter()
964 .filter_map(|statement| statement.value.as_reference()),
965 );
966 }
967 }
968 Ok(held)
969 }
970
971 fn check_movable(
974 &self,
975 from: SpaceId,
976 entity: EntityId,
977 ) -> Result<BTreeSet<TypeName>, NodeError> {
978 let open = self.space(from)?;
979 let state = open.stored.log().state();
980 let kinds = state.types(entity)?;
981 if OWN_RECORDS.iter().any(|own| kinds.contains(own))
982 || kinds
983 .iter()
984 .any(|kind| kind.as_str().starts_with("org.nibkeep.") && *kind != MEMBERSHIP)
985 {
986 return Err(NodeError::OwnRecord(entity.to_string()));
987 }
988 Ok(kinds)
989 }
990
991 fn carried_of(
1002 &self,
1003 (from, to): (SpaceId, SpaceId),
1004 entity: EntityId,
1005 (history, secrets): (MoveHistory, MoveSecrets),
1006 moving: &BTreeSet<EntityId>,
1007 ) -> Result<Vec<Carried>, NodeError> {
1008 let open = self.space(from)?;
1009 let log = open.stored.log();
1010 let state = log.state();
1011 let storage = state.storage();
1012 let last_writer_wins = open.types.last_writer_wins_fields();
1013 let secret_here = open.stored.secret_fields();
1014 let mut carried = Vec::new();
1015 for member in state.merged(entity)? {
1016 for (field, ids) in storage.of_entity(member)? {
1017 if [
1018 fields::DELETED,
1019 fields::MERGED_INTO,
1020 fields::MOVED_INTO,
1021 fields::PURGE_ASKED,
1022 ]
1023 .contains(&field)
1024 {
1025 continue;
1026 }
1027 let shown = if last_writer_wins.contains(&field) {
1028 state
1029 .last_written(entity, &field)?
1030 .map(|statement| statement.id)
1031 } else {
1032 None
1033 };
1034 for id in ids {
1035 if last_writer_wins.contains(&field) && shown != Some(id) {
1036 continue;
1037 }
1038 let Some(recorded) = storage.get(id)? else {
1039 continue;
1040 };
1041 let replaced = storage.superseded_at(id)?;
1042 if history == MoveHistory::Leave && replaced.is_some() {
1043 continue;
1044 }
1045 let secret = secret_here.contains(&field) || storage.is_secret(id)?;
1046 if secret && secrets == MoveSecrets::Leave {
1047 continue;
1048 }
1049 let mut statement = recorded.statement.into_owned();
1050 let mut there = false;
1051 if let Value::Reference(target) = statement.value {
1052 let target = state.canonical(target)?;
1053 statement.value = Value::Reference(target);
1054 if !moving.contains(&target)
1055 && let Some((space, now)) = self.moved_into(from, target)?
1056 && space == to
1057 {
1058 statement.value = Value::Reference(now);
1059 there = true;
1060 }
1061 }
1062 if replaced.is_none()
1063 && statement.field == IN_FOLDER
1064 && !there
1065 && statement
1066 .value
1067 .as_reference()
1068 .is_some_and(|folder| !moving.contains(&folder))
1069 {
1070 continue;
1071 }
1072 let (recorded, author) = match history {
1073 MoveHistory::Bring => (Some(recorded.at), log.author_of(id)?),
1074 MoveHistory::Leave => (None, None),
1075 };
1076 carried.push(Carried {
1077 statement,
1078 secret,
1079 recorded,
1080 author,
1081 replaced,
1082 });
1083 }
1084 }
1085 }
1086 Ok(carried)
1087 }
1088
1089 fn staying_holders(
1091 &self,
1092 from: SpaceId,
1093 entities: &[EntityId],
1094 ) -> Result<Vec<EntityId>, NodeError> {
1095 let open = self.space(from)?;
1096 let state = open.stored.log().state();
1097 let moving: BTreeSet<EntityId> = entities.iter().copied().collect();
1098 let mut staying = BTreeSet::new();
1099 for &entity in entities {
1100 for statement in &state.current(entity, &IN_FOLDER)? {
1101 if let Some(folder) = statement.value.as_reference() {
1102 staying.insert(state.canonical(folder)?);
1103 }
1104 }
1105 for membership in open.stored.find(&fields::ITEM, &Value::Reference(entity))? {
1106 let membership = state.canonical(membership)?;
1107 if !state.types(membership)?.contains(&MEMBERSHIP)
1108 || state.is_deleted(membership)?
1109 {
1110 continue;
1111 }
1112 for statement in &state.current(membership, &fields::LIST)? {
1113 if let Some(list) = statement.value.as_reference() {
1114 staying.insert(state.canonical(list)?);
1115 }
1116 }
1117 }
1118 }
1119 let mut here = Vec::new();
1121 for holder in staying {
1122 if !moving.contains(&holder) && self.moved_into(from, holder)?.is_none() {
1123 here.push(holder);
1124 }
1125 }
1126 Ok(here)
1127 }
1128
1129 fn copy_blob(
1140 &mut self,
1141 from: SpaceId,
1142 content: &Hash,
1143 (to, secret): (SpaceId, bool),
1144 wall_millis: u64,
1145 rng: &mut impl CryptoRng,
1146 ) -> Result<(), NodeError> {
1147 if !self
1148 .space(to)?
1149 .stored
1150 .held_copies(content, secret)
1151 .is_empty()
1152 {
1153 return Ok(());
1154 }
1155 let held = self.space(from)?.stored.holds_blob(content);
1156 let originals = if held {
1157 Vec::new()
1158 } else {
1159 self.originals_here(from, content)?
1160 };
1161 let mut target = self.spaces.remove(&to).ok_or(NodeError::NoSpace(to))?;
1162 let copied = (|| {
1163 let source = self.space(from)?;
1164 for (sealed, key) in source.stored.held_copies(content, secret) {
1165 let shared = target.stored.share_blob(
1166 &target.keys,
1167 content,
1168 (sealed, &key),
1169 secret,
1170 wall_millis,
1171 rng,
1172 )?;
1173 if shared {
1174 return Ok(());
1175 }
1176 }
1177 let others = &self.spaces;
1179 let elsewhere = |content: &Hash| {
1180 held_copies_in(
1181 others
1182 .iter()
1183 .filter(|(id, _)| **id != from)
1184 .map(|(_, open)| open),
1185 content,
1186 secret,
1187 )
1188 };
1189 let sealed = if held {
1190 let reader = source.stored.open_blob(content)?;
1191 target.stored.import_blob_sharing(
1192 &target.keys,
1193 (reader, secret),
1194 &elsewhere,
1195 wall_millis,
1196 rng,
1197 )?
1198 } else {
1199 let mut sealed = None;
1200 for original in &originals {
1201 if let Ok(file) = File::open(original) {
1202 sealed = Some(target.stored.import_blob_sharing(
1203 &target.keys,
1204 (file, secret),
1205 &elsewhere,
1206 wall_millis,
1207 rng,
1208 )?);
1209 break;
1210 }
1211 }
1212 sealed.ok_or_else(|| NodeError::NotHere(content.to_string()))?
1213 };
1214 if sealed == *content {
1215 Ok(())
1216 } else {
1217 Err(NodeError::NotHere(content.to_string()))
1218 }
1219 })();
1220 self.spaces.insert(to, target);
1221 copied
1222 }
1223}
1224
1225fn carried_operations(
1233 carried: &[Carried],
1234 (new, moved): (EntityId, &BTreeMap<EntityId, EntityId>),
1235 (from, history): (SpaceId, MoveHistory),
1236 rng: &mut impl CryptoRng,
1237) -> Vec<Operation> {
1238 let mut carried: Vec<&Carried> = carried.iter().collect();
1239 carried.sort_by_key(|each| each.statement.id);
1240 let mut ids: Vec<StatementId> = carried.iter().map(|_| StatementId::random(rng)).collect();
1241 ids.sort();
1242 let renamed: BTreeMap<StatementId, StatementId> = carried
1243 .iter()
1244 .zip(&ids)
1245 .map(|(each, id)| (each.statement.id, *id))
1246 .collect();
1247 let mut operations = Vec::new();
1248 let mut replaced = Vec::new();
1249 for (each, id) in carried.into_iter().zip(ids) {
1250 let mut qualifiers = each.statement.qualifiers.clone();
1251 if let Some(first) = qualifiers.alternative()
1252 && let Some(new) = renamed.get(&first)
1253 {
1254 let alternative: FieldName = fields::ALTERNATIVE;
1255 qualifiers.insert(alternative, Value::Text(new.to_string()));
1256 }
1257 if history == MoveHistory::Bring {
1258 let millis =
1259 |at: Timestamp| Value::Integer(i64::try_from(at.millis()).unwrap_or(i64::MAX));
1260 if qualifiers.get(&fields::CARRIED_FROM).is_none() {
1263 qualifiers.insert(fields::CARRIED_FROM, Value::Text(from.to_string()));
1264 if let Some(author) = &each.author {
1265 qualifiers.insert(fields::CARRIED_BY, Value::Text(author.to_text()));
1266 }
1267 if let Some(at) = each.recorded {
1268 qualifiers.insert(fields::CARRIED_AT, millis(at));
1269 }
1270 if let Some(at) = each.replaced {
1271 qualifiers.insert(fields::CARRIED_REPLACED, millis(at));
1272 }
1273 }
1274 }
1275 let value = match &each.statement.value {
1276 Value::Reference(target) => {
1277 Value::Reference(moved.get(target).copied().unwrap_or(*target))
1278 }
1279 value => value.clone(),
1280 };
1281 operations.push(Operation::assert(Statement {
1282 id,
1283 entity: new,
1284 field: each.statement.field.clone(),
1285 value,
1286 qualifiers,
1287 }));
1288 if each.replaced.is_some() {
1289 replaced.push(id);
1290 }
1291 }
1292 if !replaced.is_empty() {
1293 operations.push(Operation::retract(new, replaced));
1294 }
1295 operations
1296}