1use std::collections::{BTreeMap, BTreeSet};
8use std::fs;
9use std::path::Path;
10
11use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
12use nibkeep_crypto::rand_core::CryptoRng;
13use nibkeep_log::list::{is_position, position_between};
14use nibkeep_model::storage::Statements;
15use nibkeep_model::{
16 FieldDef, FieldName, Name, Operation, Resolution, State, Statement, TypeDef, TypeName, Value,
17 ValueKind, fields,
18};
19use nibkeep_std::{
20 CAMERA_MAKE, CONTENT, FILE, FOUND_ON, MEDIA_TYPE, MODIFIED, ORIGIN, ORIGIN_OF, PATH, SIZE,
21};
22
23use super::Library;
24use super::accounts::Copies;
25use super::entities::{PART, by_parts};
26use super::files::{moment, resolved_path};
27use crate::NodeError;
28
29pub const STORAGE_POLICY: TypeName = TypeName::from_static("org.nibkeep.storage-policy");
31
32pub const STORAGE_RULE: TypeName = TypeName::from_static("org.nibkeep.storage-rule");
34
35pub const POLICY: FieldName = FieldName::from_static("org.nibkeep.policy");
37
38pub(crate) const POLICY_COPIES: FieldName = FieldName::from_static("org.nibkeep.policy-copies");
40
41pub(crate) const POLICY_AWAY: FieldName = FieldName::from_static("org.nibkeep.policy-away");
43
44pub(crate) const POLICY_ARCHIVED: FieldName = FieldName::from_static("org.nibkeep.policy-archived");
46
47pub(crate) const POLICY_KEPT: FieldName = FieldName::from_static("org.nibkeep.policy-kept");
49
50pub(crate) const RULE_POLICY: FieldName = FieldName::from_static("org.nibkeep.rule-policy");
52
53pub(crate) const RULE_TYPE: FieldName = FieldName::from_static("org.nibkeep.rule-type");
55
56pub(crate) const RULE_HAS: FieldName = FieldName::from_static("org.nibkeep.rule-has");
58
59pub(crate) const RULE_FOLDER: FieldName = FieldName::from_static("org.nibkeep.rule-folder");
62
63pub(crate) const RULE_DEVICE: FieldName = FieldName::from_static("org.nibkeep.rule-device");
65
66pub(crate) const RULE_MEDIA_TYPE: FieldName = FieldName::from_static("org.nibkeep.rule-media-type");
68
69pub(crate) const RULE_LARGER_THAN: FieldName =
71 FieldName::from_static("org.nibkeep.rule-larger-than");
72
73pub(crate) const RULE_ASKS_ABOVE: FieldName = FieldName::from_static("org.nibkeep.rule-asks-above");
76
77const OWN_FIELDS: [FieldName; 13] = [
80 POLICY,
81 POLICY_COPIES,
82 POLICY_AWAY,
83 POLICY_ARCHIVED,
84 POLICY_KEPT,
85 RULE_POLICY,
86 RULE_TYPE,
87 RULE_HAS,
88 RULE_FOLDER,
89 RULE_DEVICE,
90 RULE_MEDIA_TYPE,
91 RULE_LARGER_THAN,
92 RULE_ASKS_ABOVE,
93];
94
95pub(crate) fn is_own_field(field: &FieldName) -> bool {
98 OWN_FIELDS.contains(field) || super::backups::is_own_field(field)
99}
100
101pub(crate) fn is_own_type(name: &TypeName) -> bool {
104 *name == STORAGE_POLICY || *name == STORAGE_RULE || *name == super::backups::BACKUP
105}
106
107pub(crate) fn types() -> [TypeDef; 2] {
109 let integer = || FieldDef::new(ValueKind::Integer);
110 let text = || FieldDef::new(ValueKind::Text);
111 [
112 TypeDef::new(STORAGE_POLICY, 1)
113 .with_field(fields::NAME, FieldDef::new(ValueKind::Name))
114 .with_field(POLICY_COPIES, integer())
115 .with_field(POLICY_AWAY, integer())
116 .with_field(POLICY_ARCHIVED, integer())
117 .with_field(POLICY_KEPT, text()),
118 TypeDef::new(STORAGE_RULE, 1)
119 .with_field(fields::POSITION, text().last_writer_wins())
120 .with_field(RULE_POLICY, FieldDef::new(ValueKind::Reference))
121 .with_field(RULE_TYPE, text())
122 .with_field(RULE_HAS, text())
123 .with_field(RULE_FOLDER, text())
124 .with_field(RULE_DEVICE, FieldDef::new(ValueKind::Reference))
125 .with_field(RULE_MEDIA_TYPE, text())
126 .with_field(RULE_LARGER_THAN, integer())
127 .with_field(RULE_ASKS_ABOVE, integer()),
128 ]
129}
130
131#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
133pub enum Kept {
134 InPlace,
136 Store,
138}
139
140impl Kept {
141 #[must_use]
143 pub const fn as_str(self) -> &'static str {
144 match self {
145 Self::InPlace => "in-place",
146 Self::Store => "store",
147 }
148 }
149}
150
151#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
153pub struct Needs {
154 pub copies: u32,
156 pub away: u32,
158 pub archived: u32,
160 pub kept: Kept,
162}
163
164impl Needs {
165 pub const CRITICAL: Self = Self {
168 copies: 3,
169 away: 1,
170 archived: 0,
171 kept: Kept::Store,
172 };
173
174 pub const ONE: Self = Self {
177 copies: 1,
178 away: 0,
179 archived: 0,
180 kept: Kept::Store,
181 };
182
183 pub const FALLBACK: Self = Self {
186 copies: 2,
187 away: 0,
188 archived: 1,
189 kept: Kept::Store,
190 };
191
192 #[must_use]
195 pub fn lacks(&self, disks: usize, away: usize, archived: usize) -> Lacks {
196 let needs = |wanted: u32| usize::try_from(wanted).unwrap_or(usize::MAX);
197 Lacks {
198 copies: disks < needs(self.copies.max(1)),
199 away: away < needs(self.away),
200 archived: archived < needs(self.archived),
201 }
202 }
203
204 #[must_use]
207 pub fn lacks_of(&self, copies: &[super::accounts::FileCopy]) -> Lacks {
208 let counting = || copies.iter().filter(|copy| copy.counts);
209 self.lacks(
210 counting().count(),
211 counting().filter(|copy| copy.disk.away).count(),
212 counting().filter(|copy| copy.disk.archive).count(),
213 )
214 }
215
216 #[must_use]
218 pub fn strictest(self, other: Self) -> Self {
219 Self {
220 copies: self.copies.max(other.copies),
221 away: self.away.max(other.away),
222 archived: self.archived.max(other.archived),
223 kept: self.kept.max(other.kept),
224 }
225 }
226}
227
228#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
230pub struct Lacks {
231 pub copies: bool,
233 pub away: bool,
235 pub archived: bool,
237}
238
239impl Lacks {
240 #[must_use]
242 pub fn any(self) -> bool {
243 self.copies || self.away || self.archived
244 }
245}
246
247#[derive(Clone, Debug, PartialEq, Eq)]
249pub struct Policy {
250 pub id: EntityId,
252 pub name: Option<String>,
254 pub needs: Needs,
256}
257
258#[derive(Clone, Debug, PartialEq, Eq)]
260pub struct Folder {
261 pub path: String,
263 pub device: EntityId,
265}
266
267#[derive(Clone, Debug, Default, PartialEq, Eq)]
270pub struct Conditions {
271 pub of_type: Option<TypeName>,
273 pub has: Option<FieldName>,
275 pub folder: Option<Folder>,
277 pub media_type: Option<String>,
279 pub larger_than: Option<u64>,
281}
282
283impl Conditions {
284 #[must_use]
286 pub fn is_empty(&self) -> bool {
287 *self == Self::default()
288 }
289
290 fn hold(&self, facts: &Facts) -> bool {
292 self.of_type
293 .as_ref()
294 .is_none_or(|name| facts.types.contains(name))
295 && self
296 .has
297 .as_ref()
298 .is_none_or(|field| facts.fields.contains(field))
299 && self.folder.as_ref().is_none_or(|folder| {
300 !facts.places.is_empty()
301 && facts.places.iter().all(|(device, path)| {
302 *device == folder.device && Path::new(path).starts_with(&folder.path)
303 })
304 })
305 && self.media_type.as_ref().is_none_or(|prefix| {
306 facts
307 .media_type
308 .as_ref()
309 .is_some_and(|media_type| media_type.starts_with(prefix.as_str()))
310 })
311 && self
312 .larger_than
313 .is_none_or(|bytes| facts.size.is_some_and(|size| size > bytes))
314 }
315}
316
317#[derive(Clone, Debug, PartialEq, Eq)]
319pub struct Rule {
320 pub id: EntityId,
322 pub policy: Option<EntityId>,
324 pub conditions: Conditions,
326 pub asks_above: Option<u64>,
329 position: Option<String>,
331}
332
333#[derive(Clone, Debug, PartialEq, Eq)]
335pub struct NewRule {
336 pub policy: EntityId,
338 pub of_type: Option<TypeName>,
340 pub has: Option<FieldName>,
342 pub folder: Option<std::path::PathBuf>,
344 pub media_type: Option<String>,
346 pub larger_than: Option<u64>,
348 pub asks_above: Option<u64>,
350}
351
352impl NewRule {
353 #[must_use]
355 pub const fn new(policy: EntityId) -> Self {
356 Self {
357 policy,
358 of_type: None,
359 has: None,
360 folder: None,
361 media_type: None,
362 larger_than: None,
363 asks_above: None,
364 }
365 }
366}
367
368#[derive(Clone, Copy, Debug, PartialEq, Eq)]
370pub enum Place {
371 First,
373 Last,
375 Before(EntityId),
377 After(EntityId),
379 BeforeTheRest,
382}
383
384#[derive(Clone, Copy, Debug, PartialEq, Eq)]
386pub enum ChosenBy {
387 Own,
389 Rule(EntityId),
391 Fallback,
393}
394
395#[derive(Clone, Debug, PartialEq, Eq)]
397pub struct Choice {
398 pub policy: Option<EntityId>,
400 pub needs: Needs,
402 pub by: ChosenBy,
404 pub asks_above: Option<u64>,
407}
408
409#[derive(Clone, Debug, PartialEq, Eq)]
411pub struct PolicyCount {
412 pub policy: Option<EntityId>,
414 pub name: Option<String>,
416 pub needs: Needs,
418 pub files: usize,
420 pub short: usize,
423 pub lacking: Vec<EntityId>,
425 pub few_copies: usize,
427 pub few_away: usize,
429 pub few_archived: usize,
431 pub unchecked: usize,
436 pub none_here: Vec<EntityId>,
439 pub not_stored: Vec<EntityId>,
442}
443
444#[derive(Clone, Debug, Default, PartialEq, Eq)]
449pub struct PolicyCheck {
450 pub policies: Vec<PolicyCount>,
453 pub disks: Vec<super::accounts::Disk>,
455 pub changes: super::accounts::ChangeCopies,
457 pub files: Vec<CheckedFile>,
460}
461
462#[derive(Clone, Debug, PartialEq, Eq)]
465pub struct CheckedFile {
466 pub file: EntityId,
468 pub policy: Option<EntityId>,
470 pub size: Option<u64>,
472 pub disks: usize,
474 pub away: usize,
476 pub archived: usize,
478 pub lacks: Lacks,
480 pub unchecked: bool,
483}
484
485#[derive(Clone, Debug, Default)]
487pub(crate) struct Facts {
488 pub(crate) types: BTreeSet<TypeName>,
489 pub(crate) fields: BTreeSet<FieldName>,
490 pub(crate) media_type: Option<String>,
491 pub(crate) size: Option<u64>,
492 pub(crate) places: Vec<(EntityId, String)>,
494}
495
496pub(crate) struct Policies {
498 policies: BTreeMap<EntityId, Policy>,
499 rules: Vec<Rule>,
500}
501
502impl Policies {
503 pub(crate) fn read<S: Statements>(
505 state: &State<S>,
506 policies: impl IntoIterator<Item = EntityId>,
507 rules: impl IntoIterator<Item = EntityId>,
508 ) -> Result<Self, NodeError>
509 where
510 NodeError: From<S::Error>,
511 {
512 let mut read = BTreeMap::new();
513 for entity in policies {
514 let entity = state.canonical(entity)?;
515 if state.is_deleted(entity)? || !state.types(entity)?.contains(&STORAGE_POLICY) {
516 continue;
517 }
518 read.insert(entity, read_policy(state, entity)?);
519 }
520 let mut found = Vec::new();
521 for entity in rules {
522 let entity = state.canonical(entity)?;
523 if state.is_deleted(entity)? || !state.types(entity)?.contains(&STORAGE_RULE) {
524 continue;
525 }
526 found.push(read_rule(state, entity, &read)?);
527 }
528 found.sort_by(|a, b| {
529 (a.position.is_none(), &a.position, a.id).cmp(&(
530 b.position.is_none(),
531 &b.position,
532 b.id,
533 ))
534 });
535 found.dedup_by_key(|rule| rule.id);
536 Ok(Self {
537 policies: read,
538 rules: found,
539 })
540 }
541
542 pub(crate) fn choose(&self, own: &[EntityId], facts: &Facts) -> Choice {
544 if let Some(policy) = self.strictest(own) {
545 return Choice {
546 policy: Some(policy.id),
547 needs: policy.needs,
548 by: ChosenBy::Own,
549 asks_above: None,
550 };
551 }
552 for rule in &self.rules {
553 if let Some(policy) = rule.policy.and_then(|id| self.policies.get(&id))
554 && rule.conditions.hold(facts)
555 {
556 return Choice {
557 policy: Some(policy.id),
558 needs: policy.needs,
559 by: ChosenBy::Rule(rule.id),
560 asks_above: rule.asks_above,
561 };
562 }
563 }
564 Choice {
565 policy: None,
566 needs: Needs::FALLBACK,
567 by: ChosenBy::Fallback,
568 asks_above: None,
569 }
570 }
571
572 pub(crate) fn asks_about(&self, size: u64) -> bool {
575 self.rules
576 .iter()
577 .any(|rule| rule.asks_above.is_some_and(|limit| size > limit))
578 }
579
580 pub(crate) fn has_policy(&self, id: EntityId) -> bool {
582 self.policies.contains_key(&id)
583 }
584
585 pub(crate) fn has_rule(&self, id: EntityId) -> bool {
587 self.rules.iter().any(|rule| rule.id == id)
588 }
589
590 fn strictest(&self, ids: &[EntityId]) -> Option<&Policy> {
592 ids.iter()
593 .filter_map(|id| self.policies.get(id))
594 .max_by_key(|policy| (policy.needs, std::cmp::Reverse(policy.id)))
595 }
596
597 pub(crate) fn fields_asked(&self) -> BTreeSet<FieldName> {
599 self.rules
600 .iter()
601 .filter_map(|rule| rule.conditions.has.clone())
602 .collect()
603 }
604}
605
606fn read_policy<S: Statements>(state: &State<S>, entity: EntityId) -> Result<Policy, NodeError>
610where
611 NodeError: From<S::Error>,
612{
613 let most = |field: &FieldName| -> Result<u32, NodeError> {
614 Ok(state
615 .current(entity, field)?
616 .iter()
617 .filter_map(|statement| match statement.value {
618 Value::Integer(n) => u32::try_from(n).ok(),
619 _ => None,
620 })
621 .max()
622 .unwrap_or(0))
623 };
624 let kept: Vec<String> = state
625 .current(entity, &POLICY_KEPT)?
626 .iter()
627 .filter_map(|statement| statement.value.as_text().map(str::to_owned))
628 .collect();
629 let kept = if kept.is_empty() || kept.iter().any(|kept| kept != Kept::InPlace.as_str()) {
630 Kept::Store
631 } else {
632 Kept::InPlace
633 };
634 Ok(Policy {
635 id: entity,
636 name: first_name(state, entity)?,
637 needs: Needs {
638 copies: most(&POLICY_COPIES)?.max(1),
639 away: most(&POLICY_AWAY)?,
640 archived: most(&POLICY_ARCHIVED)?,
641 kept,
642 },
643 })
644}
645
646fn read_rule<S: Statements>(
649 state: &State<S>,
650 entity: EntityId,
651 policies: &BTreeMap<EntityId, Policy>,
652) -> Result<Rule, NodeError>
653where
654 NodeError: From<S::Error>,
655{
656 let first = |field: &FieldName| -> Result<Option<Value>, NodeError> {
657 Ok(state
658 .current(entity, field)?
659 .iter()
660 .min_by_key(|statement| statement.id)
661 .map(|statement| statement.value.clone()))
662 };
663 let text = |field: &FieldName| -> Result<Option<String>, NodeError> {
664 Ok(first(field)?.and_then(|value| value.as_text().map(str::to_owned)))
665 };
666 let bytes = |field: &FieldName| -> Result<Option<u64>, NodeError> {
667 Ok(match first(field)? {
668 Some(Value::Integer(n)) => u64::try_from(n).ok(),
669 _ => None,
670 })
671 };
672 let mut named = Vec::new();
673 for statement in state.current(entity, &RULE_POLICY)? {
674 if let Some(policy) = statement.value.as_reference() {
675 named.push(state.canonical(policy)?);
676 }
677 }
678 let policy = named
679 .iter()
680 .filter_map(|id| policies.get(id))
681 .max_by_key(|policy| (policy.needs, std::cmp::Reverse(policy.id)))
682 .map(|policy| policy.id);
683 let device = match first(&RULE_DEVICE)? {
684 Some(Value::Reference(device)) => Some(state.canonical(device)?),
685 _ => None,
686 };
687 let folder = match (text(&RULE_FOLDER)?, device) {
688 (Some(path), Some(device)) => Some(Folder { path, device }),
689 _ => None,
690 };
691 let conditions = Conditions {
692 of_type: text(&RULE_TYPE)?.and_then(|name| name.parse().ok()),
693 has: text(&RULE_HAS)?.and_then(|name| name.parse().ok()),
694 folder,
695 media_type: text(&RULE_MEDIA_TYPE)?,
696 larger_than: bytes(&RULE_LARGER_THAN)?,
697 };
698 let readable = [
701 (RULE_TYPE, conditions.of_type.is_some()),
702 (RULE_HAS, conditions.has.is_some()),
703 (RULE_FOLDER, conditions.folder.is_some()),
704 (RULE_DEVICE, conditions.folder.is_some()),
705 (RULE_MEDIA_TYPE, conditions.media_type.is_some()),
706 (RULE_LARGER_THAN, conditions.larger_than.is_some()),
707 ]
708 .into_iter()
709 .try_fold(true, |readable, (field, read)| {
710 Ok::<_, NodeError>(readable && (read || first(&field)?.is_none()))
711 })?;
712 Ok(Rule {
713 id: entity,
714 policy: policy.filter(|_| readable),
715 conditions,
716 asks_above: bytes(&RULE_ASKS_ABOVE)?,
717 position: last_position(state, entity)?,
718 })
719}
720
721fn last_position<S: Statements>(
723 state: &State<S>,
724 entity: EntityId,
725) -> Result<Option<String>, NodeError>
726where
727 NodeError: From<S::Error>,
728{
729 let definition = FieldDef::new(ValueKind::Text).last_writer_wins();
730 Ok(
731 match state.resolve(entity, &fields::POSITION, Some(&definition))? {
732 Resolution::Values(values) | Resolution::Competing(values) => values
733 .first()
734 .and_then(|statement| statement.value.as_text())
735 .filter(|key| is_position(key))
736 .map(str::to_owned),
737 },
738 )
739}
740
741pub(crate) fn first_name<S: Statements>(
743 state: &State<S>,
744 entity: EntityId,
745) -> Result<Option<String>, NodeError>
746where
747 NodeError: From<S::Error>,
748{
749 Ok(state
750 .current(entity, &fields::NAME)?
751 .iter()
752 .min_by_key(|statement| statement.id)
753 .and_then(|statement| statement.value.as_name_text().map(str::to_owned)))
754}
755
756pub(crate) fn facts_of<S: Statements>(state: &State<S>, file: EntityId) -> Result<Facts, NodeError>
759where
760 NodeError: From<S::Error>,
761{
762 let mut facts = facts_but_places(state, file)?;
763 facts.places = origins_of(state, file)?
764 .into_iter()
765 .map(|(_, device, path)| (device, path))
766 .collect();
767 Ok(facts)
768}
769
770fn facts_but_places<S: Statements>(state: &State<S>, file: EntityId) -> Result<Facts, NodeError>
772where
773 NodeError: From<S::Error>,
774{
775 let media_type = state
776 .current(file, &MEDIA_TYPE)?
777 .iter()
778 .min_by_key(|statement| statement.id)
779 .and_then(|statement| statement.value.as_text().map(str::to_owned));
780 Ok(Facts {
781 types: state.types(file)?,
782 fields: state.fields(file)?,
783 media_type,
784 size: size_of(state, file)?,
785 places: Vec::new(),
786 })
787}
788
789pub(crate) fn size_of<S: Statements>(
791 state: &State<S>,
792 file: EntityId,
793) -> Result<Option<u64>, NodeError>
794where
795 NodeError: From<S::Error>,
796{
797 Ok(state
798 .current(file, &SIZE)?
799 .iter()
800 .find_map(|statement| match statement.value {
801 Value::Integer(n) => u64::try_from(n).ok(),
802 _ => None,
803 }))
804}
805
806pub(crate) fn stands_here<S: Statements>(
809 state: &State<S>,
810 record: EntityId,
811) -> Result<bool, NodeError>
812where
813 NodeError: From<S::Error>,
814{
815 Ok(!state.is_deleted(record)? && state.current(record, &fields::MOVED_INTO)?.is_empty())
816}
817
818pub(crate) fn origins_of<S: Statements>(
821 state: &State<S>,
822 file: EntityId,
823) -> Result<Vec<(EntityId, EntityId, String)>, NodeError>
824where
825 NodeError: From<S::Error>,
826{
827 let mut found = Vec::new();
828 let mut seen = BTreeSet::new();
829 for statement in state.referrers_in(file, &ORIGIN_OF)? {
830 let origin = state.canonical(statement.entity)?;
831 if !seen.insert(origin)
832 || !stands_here(state, origin)?
833 || !state.types(origin)?.contains(&ORIGIN)
834 {
835 continue;
836 }
837 let devices: Vec<EntityId> = state
838 .current(origin, &FOUND_ON)?
839 .iter()
840 .filter_map(|statement| statement.value.as_reference())
841 .collect();
842 for path in state.current(origin, &PATH)? {
843 if let Some(path) = path.value.as_text() {
844 for device in &devices {
845 found.push((origin, state.canonical(*device)?, path.to_owned()));
846 }
847 }
848 }
849 }
850 Ok(found)
851}
852
853fn derived(space: SpaceId, label: &str) -> EntityId {
856 let material = [space.as_bytes().as_slice(), label.as_bytes()].concat();
857 EntityId::derived("nibkeep 2026-10 storage policies", &material)
858}
859
860const CRITICAL: &str = "critical";
862const STANDARD: &str = "standard";
863const REPLACEABLE: &str = "replaceable";
864
865const FROM_A_CAMERA: &str = "from a camera";
868const ANY_OTHER: &str = "any other file";
869const DOWNLOADS: &str = "downloads";
870
871const ASKS_ABOVE: u64 = 1 << 30;
874
875pub(crate) fn default_policies(space: SpaceId) -> [EntityId; 3] {
878 [CRITICAL, STANDARD, REPLACEABLE].map(|label| derived(space, label))
879}
880
881pub(crate) fn answer_policy(space: SpaceId, again: bool) -> EntityId {
884 derived(space, if again { REPLACEABLE } else { STANDARD })
885}
886
887pub(crate) fn assert(
889 entity: EntityId,
890 field: FieldName,
891 value: Value,
892 rng: &mut impl CryptoRng,
893) -> Operation {
894 Operation::assert(Statement::new(
895 StatementId::random(rng),
896 entity,
897 field,
898 value,
899 ))
900}
901
902fn make_policy(
904 entity: EntityId,
905 name: &str,
906 needs: Needs,
907 rng: &mut impl CryptoRng,
908) -> Vec<Operation> {
909 vec![
910 assert(
911 entity,
912 fields::TYPE,
913 Value::Text(STORAGE_POLICY.to_string()),
914 rng,
915 ),
916 assert(entity, fields::NAME, Value::Name(Name::new(name)), rng),
917 assert(
918 entity,
919 POLICY_COPIES,
920 Value::Integer(i64::from(needs.copies)),
921 rng,
922 ),
923 assert(
924 entity,
925 POLICY_AWAY,
926 Value::Integer(i64::from(needs.away)),
927 rng,
928 ),
929 assert(
930 entity,
931 POLICY_ARCHIVED,
932 Value::Integer(i64::from(needs.archived)),
933 rng,
934 ),
935 assert(
936 entity,
937 POLICY_KEPT,
938 Value::Text(needs.kept.as_str().to_owned()),
939 rng,
940 ),
941 ]
942}
943
944fn make_rule(
947 entity: EntityId,
948 rule: &NewRule,
949 folder: Option<(&str, EntityId)>,
950 position: String,
951 rng: &mut impl CryptoRng,
952) -> Vec<Operation> {
953 let mut operations = vec![
954 assert(
955 entity,
956 fields::TYPE,
957 Value::Text(STORAGE_RULE.to_string()),
958 rng,
959 ),
960 assert(entity, fields::POSITION, Value::Text(position), rng),
961 assert(entity, RULE_POLICY, Value::Reference(rule.policy), rng),
962 ];
963 if let Some(name) = &rule.of_type {
964 operations.push(assert(
965 entity,
966 RULE_TYPE,
967 Value::Text(name.to_string()),
968 rng,
969 ));
970 }
971 if let Some(field) = &rule.has {
972 operations.push(assert(
973 entity,
974 RULE_HAS,
975 Value::Text(field.to_string()),
976 rng,
977 ));
978 }
979 if let Some((path, device)) = folder {
980 operations.push(assert(
981 entity,
982 RULE_FOLDER,
983 Value::Text(path.to_owned()),
984 rng,
985 ));
986 operations.push(assert(entity, RULE_DEVICE, Value::Reference(device), rng));
987 }
988 if let Some(media_type) = &rule.media_type {
989 operations.push(assert(
990 entity,
991 RULE_MEDIA_TYPE,
992 Value::Text(media_type.clone()),
993 rng,
994 ));
995 }
996 for (field, bytes) in [
997 (RULE_LARGER_THAN, rule.larger_than),
998 (RULE_ASKS_ABOVE, rule.asks_above),
999 ] {
1000 if let Some(bytes) = bytes {
1001 operations.push(assert(
1002 entity,
1003 field,
1004 Value::Integer(i64::try_from(bytes).unwrap_or(i64::MAX)),
1005 rng,
1006 ));
1007 }
1008 }
1009 operations
1010}
1011
1012fn resolved_folder(folder: &Path) -> Result<String, NodeError> {
1015 let resolved = resolved_path(folder).map_err(|error| NodeError::Unreadable {
1016 path: folder.display().to_string(),
1017 reason: error.to_string(),
1018 })?;
1019 if !resolved.is_dir() {
1020 return Err(NodeError::Unreadable {
1021 path: folder.display().to_string(),
1022 reason: "not a folder".to_owned(),
1023 });
1024 }
1025 Ok(resolved.to_string_lossy().into_owned())
1026}
1027
1028impl Library {
1029 pub fn install_policies(
1041 &mut self,
1042 space: SpaceId,
1043 downloads: Option<&Path>,
1044 wall_millis: u64,
1045 rng: &mut impl CryptoRng,
1046 ) -> Result<(), NodeError> {
1047 let critical = derived(space, CRITICAL);
1048 let standard = derived(space, STANDARD);
1049 let replaceable = derived(space, REPLACEABLE);
1050 let any_other = derived(space, ANY_OTHER);
1051 let device = self.info.device;
1052 let downloads_rule = derived(space, &format!("{DOWNLOADS} {device}"));
1053 let (installed, has_downloads) = {
1054 let open = self.space(space)?;
1055 let storage = open.stored.log().state().storage();
1056 let policies = open
1058 .stored
1059 .find(&fields::TYPE, &Value::Text(STORAGE_POLICY.to_string()))?;
1060 (
1061 !storage.of_entity(critical)?.is_empty() || !policies.is_empty(),
1062 !storage.of_entity(downloads_rule)?.is_empty(),
1063 )
1064 };
1065 let downloads = match downloads {
1066 Some(folder) if !has_downloads => resolved_folder(folder).ok(),
1067 _ => None,
1068 };
1069 let mut operations = Vec::new();
1070 if !installed {
1071 for (entity, name, needs) in [
1072 (critical, "Critical", Needs::CRITICAL),
1073 (standard, "Standard", Needs::FALLBACK),
1074 (
1075 replaceable,
1076 "Replaceable",
1077 Needs {
1078 copies: 1,
1079 away: 0,
1080 archived: 0,
1081 kept: Kept::InPlace,
1082 },
1083 ),
1084 ] {
1085 operations.extend(make_policy(entity, name, needs, rng));
1086 }
1087 let first = position_between(None, None).unwrap_or_else(|| "V".to_owned());
1088 let last = position_between(Some(&first), None).unwrap_or_else(|| "k".to_owned());
1089 let camera = NewRule {
1090 has: Some(CAMERA_MAKE),
1091 ..NewRule::new(standard)
1092 };
1093 operations.extend(make_rule(
1094 derived(space, FROM_A_CAMERA),
1095 &camera,
1096 None,
1097 first,
1098 rng,
1099 ));
1100 let rest = NewRule {
1101 asks_above: Some(ASKS_ABOVE),
1102 ..NewRule::new(standard)
1103 };
1104 operations.extend(make_rule(any_other, &rest, None, last, rng));
1105 }
1106 if let Some(folder) = downloads {
1107 let rule = NewRule::new(replaceable);
1108 let position = if installed {
1109 let (position, renumbered) = self.placing(space, Place::BeforeTheRest, None)?;
1110 operations.extend(self.renumbering(space, renumbered, rng)?);
1111 position
1112 } else {
1113 let first = position_between(None, None).unwrap_or_else(|| "V".to_owned());
1115 let last = position_between(Some(&first), None).unwrap_or_else(|| "k".to_owned());
1116 position_between(Some(&first), Some(&last)).unwrap_or(last)
1117 };
1118 operations.extend(make_rule(
1119 downloads_rule,
1120 &rule,
1121 Some((&folder, device)),
1122 position,
1123 rng,
1124 ));
1125 }
1126 if operations.is_empty() {
1127 return Ok(());
1128 }
1129 self.commit(space, operations, wall_millis, rng)
1130 }
1131
1132 pub(crate) fn read_policies(&self, space: SpaceId) -> Result<Policies, NodeError> {
1134 let open = self.space(space)?;
1135 let state = open.stored.log().state();
1136 let of_type = |name: &TypeName| {
1137 open.stored
1138 .find(&fields::TYPE, &Value::Text(name.to_string()))
1139 };
1140 Policies::read(state, of_type(&STORAGE_POLICY)?, of_type(&STORAGE_RULE)?)
1141 }
1142
1143 pub fn policies(&self, space: SpaceId) -> Result<Vec<Policy>, NodeError> {
1149 let mut policies: Vec<Policy> = self.read_policies(space)?.policies.into_values().collect();
1150 policies.sort_by_cached_key(|policy| {
1151 (
1152 policy.name.as_ref().map(|name| name.to_lowercase()),
1153 policy.id,
1154 )
1155 });
1156 Ok(policies)
1157 }
1158
1159 pub fn rules(&self, space: SpaceId) -> Result<Vec<Rule>, NodeError> {
1165 Ok(self.read_policies(space)?.rules)
1166 }
1167
1168 pub fn find_policy(&self, space: SpaceId, reference: &str) -> Result<EntityId, NodeError> {
1176 let policies = self.policies(space)?;
1177 let lowered = reference.to_lowercase();
1178 let by_name: Vec<EntityId> = policies
1179 .iter()
1180 .filter(|policy| {
1181 policy
1182 .name
1183 .as_ref()
1184 .is_some_and(|name| name.to_lowercase() == lowered)
1185 })
1186 .map(|policy| policy.id)
1187 .collect();
1188 let found = if by_name.is_empty() {
1189 policies
1190 .iter()
1191 .filter(|policy| {
1192 let id = policy.id.to_string();
1193 id == lowered || (lowered.len() >= 6 && id.starts_with(&lowered))
1194 })
1195 .map(|policy| policy.id)
1196 .collect()
1197 } else {
1198 by_name
1199 };
1200 match found.as_slice() {
1201 [] => Err(NodeError::NoEntity(reference.to_owned())),
1202 [one] => Ok(*one),
1203 _ => Err(NodeError::Ambiguous {
1204 reference: reference.to_owned(),
1205 candidates: found,
1206 }),
1207 }
1208 }
1209
1210 pub fn add_policy(
1217 &mut self,
1218 space: SpaceId,
1219 name: &str,
1220 needs: Needs,
1221 wall_millis: u64,
1222 rng: &mut impl CryptoRng,
1223 ) -> Result<EntityId, NodeError> {
1224 if name.trim().is_empty() {
1225 return Err(NodeError::EmptyName);
1226 }
1227 self.space(space)?;
1228 let entity = EntityId::random(rng);
1229 let operations = make_policy(
1230 entity,
1231 name.trim(),
1232 Needs {
1233 copies: needs.copies.max(1),
1234 ..needs
1235 },
1236 rng,
1237 );
1238 self.commit(space, operations, wall_millis, rng)?;
1239 Ok(entity)
1240 }
1241
1242 pub fn edit_policy(
1251 &mut self,
1252 space: SpaceId,
1253 policy: EntityId,
1254 edit: &PolicyEdit,
1255 wall_millis: u64,
1256 rng: &mut impl CryptoRng,
1257 ) -> Result<(), NodeError> {
1258 if edit
1259 .name
1260 .as_ref()
1261 .is_some_and(|name| name.trim().is_empty())
1262 {
1263 return Err(NodeError::EmptyName);
1264 }
1265 self.check_policy(space, policy)?;
1266 let mut values = Vec::new();
1267 if let Some(name) = &edit.name {
1268 values.push((fields::NAME, Value::Name(Name::new(name.trim()))));
1269 }
1270 for (field, number) in [
1271 (POLICY_COPIES, edit.copies.map(|copies| copies.max(1))),
1272 (POLICY_AWAY, edit.away),
1273 (POLICY_ARCHIVED, edit.archived),
1274 ] {
1275 if let Some(number) = number {
1276 values.push((field, Value::Integer(i64::from(number))));
1277 }
1278 }
1279 if let Some(kept) = edit.kept {
1280 values.push((POLICY_KEPT, Value::Text(kept.as_str().to_owned())));
1281 }
1282 let operations = self.replacing(space, policy, values, rng)?;
1283 if operations.is_empty() {
1284 return Ok(());
1285 }
1286 self.commit(space, operations, wall_millis, rng)
1287 }
1288
1289 pub fn add_rule(
1297 &mut self,
1298 space: SpaceId,
1299 rule: &NewRule,
1300 place: Place,
1301 wall_millis: u64,
1302 rng: &mut impl CryptoRng,
1303 ) -> Result<EntityId, NodeError> {
1304 self.check_policy(space, rule.policy)?;
1305 let folder = rule.folder.as_deref().map(resolved_folder).transpose()?;
1306 let (position, renumbered) = self.placing(space, place, None)?;
1307 let entity = EntityId::random(rng);
1308 let device = self.info.device;
1309 let mut operations = self.renumbering(space, renumbered, rng)?;
1310 operations.extend(make_rule(
1311 entity,
1312 rule,
1313 folder.as_deref().map(|folder| (folder, device)),
1314 position,
1315 rng,
1316 ));
1317 self.commit(space, operations, wall_millis, rng)?;
1318 Ok(entity)
1319 }
1320
1321 pub fn remove_rule(
1329 &mut self,
1330 space: SpaceId,
1331 rule: EntityId,
1332 wall_millis: u64,
1333 rng: &mut impl CryptoRng,
1334 ) -> Result<(), NodeError> {
1335 self.check_rule(space, rule)?;
1336 let operations = vec![assert(rule, fields::DELETED, Value::Boolean(true), rng)];
1337 self.commit(space, operations, wall_millis, rng)
1338 }
1339
1340 pub fn remove_policy(
1348 &mut self,
1349 space: SpaceId,
1350 policy: EntityId,
1351 wall_millis: u64,
1352 rng: &mut impl CryptoRng,
1353 ) -> Result<(), NodeError> {
1354 self.check_policy(space, policy)?;
1355 let operations = vec![assert(policy, fields::DELETED, Value::Boolean(true), rng)];
1356 self.commit(space, operations, wall_millis, rng)
1357 }
1358
1359 pub fn move_rule(
1366 &mut self,
1367 space: SpaceId,
1368 rule: EntityId,
1369 place: Place,
1370 wall_millis: u64,
1371 rng: &mut impl CryptoRng,
1372 ) -> Result<(), NodeError> {
1373 self.check_rule(space, rule)?;
1374 if place == Place::Before(rule) || place == Place::After(rule) {
1375 return Ok(());
1376 }
1377 let (position, mut renumbered) = self.placing(space, place, Some(rule))?;
1378 renumbered.push((rule, position));
1379 let operations = self.renumbering(space, renumbered, rng)?;
1380 self.commit(space, operations, wall_millis, rng)
1381 }
1382
1383 pub fn set_policy(
1391 &mut self,
1392 space: SpaceId,
1393 entity: EntityId,
1394 policy: Option<EntityId>,
1395 wall_millis: u64,
1396 rng: &mut impl CryptoRng,
1397 ) -> Result<(), NodeError> {
1398 if let Some(policy) = policy {
1399 self.check_policy(space, policy)?;
1400 }
1401 let operations = if let Some(policy) = policy {
1402 self.replacing(space, entity, vec![(POLICY, Value::Reference(policy))], rng)?
1403 } else {
1404 let state = self.space(space)?.stored.log().state();
1405 let current: Vec<StatementId> = state
1406 .current(entity, &POLICY)?
1407 .iter()
1408 .map(|statement| statement.id)
1409 .collect();
1410 if current.is_empty() {
1411 Vec::new()
1412 } else {
1413 vec![Operation::retract(entity, current)]
1414 }
1415 };
1416 if operations.is_empty() {
1417 return Ok(());
1418 }
1419 self.commit(space, operations, wall_millis, rng)
1420 }
1421
1422 pub fn policy_of(&self, space: SpaceId, entity: EntityId) -> Result<Choice, NodeError> {
1428 let policies = self.read_policies(space)?;
1429 let open = self.space(space)?;
1430 let state = open.stored.log().state();
1431 let entity = state.canonical(entity)?;
1432 let own = own_choices(state, entity)?;
1433 Ok(policies.choose(&own, &facts_of(state, entity)?))
1434 }
1435
1436 pub fn check_policies(
1452 &self,
1453 space: SpaceId,
1454 wall_millis: u64,
1455 ) -> Result<PolicyCheck, NodeError> {
1456 self.check_policies_in_parts(space, (PART, false), wall_millis)
1457 }
1458
1459 pub(crate) fn policies_without_this_disk(
1465 &self,
1466 space: SpaceId,
1467 wall_millis: u64,
1468 ) -> Result<Vec<PolicyCount>, NodeError> {
1469 Ok(self
1470 .check_policies_in_parts(space, (PART, true), wall_millis)?
1471 .policies)
1472 }
1473
1474 pub(crate) fn critical_needs(&self, space: SpaceId) -> Result<Needs, NodeError> {
1476 Ok(self
1477 .read_policies(space)?
1478 .policies
1479 .get(&derived(space, CRITICAL))
1480 .map_or(Needs::CRITICAL, |policy| policy.needs))
1481 }
1482
1483 fn check_policies_in_parts(
1489 &self,
1490 space: SpaceId,
1491 (part, without_own): (usize, bool),
1492 wall_millis: u64,
1493 ) -> Result<PolicyCheck, NodeError> {
1494 let policies = self.read_policies(space)?;
1495 let copies = self.copies_by_disk(space, wall_millis)?;
1496 let open = self.space(space)?;
1497 let state = open.stored.log().state();
1498 let of_type = |name: &TypeName| -> Result<Vec<EntityId>, NodeError> {
1499 Ok(open
1500 .stored
1501 .find(&fields::TYPE, &Value::Text(name.to_string()))?)
1502 };
1503 let device = self.info.device;
1505 let mut devices_needed: BTreeSet<EntityId> = policies
1506 .rules
1507 .iter()
1508 .filter_map(|rule| rule.conditions.folder.as_ref().map(|folder| folder.device))
1509 .collect();
1510 devices_needed.insert(device);
1511 let places = places_by_file(state, &of_type(&ORIGIN)?, (&devices_needed, part))?;
1512 let mut asked: Vec<FieldName> = vec![
1513 fields::TYPE,
1514 fields::DELETED,
1515 fields::MERGED_INTO,
1516 POLICY,
1517 CONTENT,
1518 SIZE,
1519 MEDIA_TYPE,
1520 ];
1521 for field in policies.fields_asked() {
1522 if !asked.contains(&field) {
1523 asked.push(field);
1524 }
1525 }
1526 let mut seen = BTreeSet::new();
1527 let mut counts: BTreeMap<Option<EntityId>, PolicyCount> = BTreeMap::new();
1528 let mut checked_files = Vec::new();
1529 by_parts(
1530 state,
1531 &of_type(&FILE)?,
1532 (&asked, part),
1533 &mut |files, ids| {
1534 for &file in ids {
1535 let file = files.canonical(file)?;
1536 if !seen.insert(file)
1537 || files.is_deleted(file)?
1538 || !files.types(file)?.contains(&FILE)
1539 {
1540 continue;
1541 }
1542 let mut found: Vec<&FoundAt> = Vec::new();
1544 for member in files.merged(file)? {
1545 found.extend(places.get(&member).into_iter().flatten());
1546 }
1547 let mut facts = facts_of_part(files, file)?;
1548 facts.places = found
1549 .iter()
1550 .map(|place| (place.device, place.path.clone()))
1551 .collect();
1552 let choice = policies.choose(&own_choices(files, file)?, &facts);
1553 let content =
1554 files
1555 .current(file, &CONTENT)?
1556 .iter()
1557 .find_map(|statement| match statement.value {
1558 Value::Blob(hash) => Some(hash),
1559 _ => None,
1560 });
1561 let stored = content.is_some_and(|hash| open.stored.holds_ordinary_blob(&hash));
1562 let members: Vec<EntityId> = files.merged(file)?.into_iter().collect();
1563 let in_place = copies.plain_here(&members, content);
1564 let sealed = self.ordinary_sealed(space, content)?;
1565 let (mut disks, old) = copies.holding(&sealed, (&members, content));
1566 if without_own && !disks.remove(&Copies::OWN) {
1567 continue;
1568 }
1569 let (away, archived) = copies.marked(&disks);
1570 checked_files.push(tally(
1571 &mut counts,
1572 &policies,
1573 (&choice, file, facts.size),
1574 (
1575 (stored, in_place),
1576 (disks.len(), away, archived, !old.is_empty()),
1577 ),
1578 ));
1579 }
1580 Ok(())
1581 },
1582 )?;
1583 let critical = policies
1584 .policies
1585 .get(&derived(space, CRITICAL))
1586 .map_or(Needs::CRITICAL, |policy| policy.needs);
1587 let mut check = checked(counts, checked_files);
1588 if without_own {
1589 check.disks = copies.disks;
1590 return Ok(check);
1591 }
1592 check.changes = self.change_copies(space, &copies, critical)?;
1593 check.disks = copies.disks;
1594 Ok(check)
1595 }
1596
1597 pub(crate) fn origin_places_here(
1604 &self,
1605 space: SpaceId,
1606 ) -> Result<Vec<super::checking::PlainPlace>, NodeError> {
1607 let open = self.space(space)?;
1608 let state = open.stored.log().state();
1609 let mut origins = Vec::new();
1611 for origin in open
1612 .stored
1613 .find(&fields::TYPE, &Value::Text(ORIGIN.to_string()))?
1614 {
1615 if stands_here(state, state.canonical(origin)?)? {
1616 origins.push(origin);
1617 }
1618 }
1619 let device = self.info.device;
1620 let mut found = Vec::new();
1621 for (file, places) in places_by_file(state, &origins, (&BTreeSet::from([device]), PART))? {
1622 for place in places.iter().filter(|place| place.device == device) {
1623 let (Some(content), Some(size)) = (place.content, place.size) else {
1624 continue;
1625 };
1626 let untouched = place.holds(Some(content));
1627 found.push(super::checking::PlainPlace {
1628 file,
1629 path: place.path.clone(),
1630 content,
1631 untouched,
1632 size,
1633 seen: super::checking::seen_at(&place.path).filter(|_| untouched),
1634 });
1635 }
1636 }
1637 Ok(found)
1638 }
1639
1640 fn check_policy(&self, space: SpaceId, policy: EntityId) -> Result<(), NodeError> {
1643 if self.read_policies(space)?.policies.contains_key(&policy) {
1644 Ok(())
1645 } else {
1646 Err(NodeError::NoEntity(policy.to_string()))
1647 }
1648 }
1649
1650 fn check_rule(&self, space: SpaceId, rule: EntityId) -> Result<(), NodeError> {
1653 if self
1654 .read_policies(space)?
1655 .rules
1656 .iter()
1657 .any(|known| known.id == rule)
1658 {
1659 Ok(())
1660 } else {
1661 Err(NodeError::NoEntity(rule.to_string()))
1662 }
1663 }
1664
1665 fn placing(
1669 &self,
1670 space: SpaceId,
1671 place: Place,
1672 moving: Option<EntityId>,
1673 ) -> Result<(String, Vec<(EntityId, String)>), NodeError> {
1674 let rules: Vec<Rule> = self
1675 .read_policies(space)?
1676 .rules
1677 .into_iter()
1678 .filter(|rule| Some(rule.id) != moving)
1679 .collect();
1680 let index_of = |id: EntityId| {
1681 rules
1682 .iter()
1683 .position(|rule| rule.id == id)
1684 .ok_or_else(|| NodeError::NoEntity(id.to_string()))
1685 };
1686 let at = match place {
1688 Place::First => 0,
1689 Place::Last => rules.len(),
1690 Place::Before(id) => index_of(id)?,
1691 Place::After(id) => index_of(id)? + 1,
1692 Place::BeforeTheRest => match rules.last() {
1693 Some(last) if last.conditions.is_empty() => rules.len() - 1,
1694 _ => rules.len(),
1695 },
1696 };
1697 let neighbour = |index: Option<usize>| match index {
1698 None => Some(None),
1699 Some(index) => rules
1700 .get(index)
1701 .map_or(Some(None), |rule| rule.position.as_deref().map(Some)),
1702 };
1703 if let (Some(before), Some(after)) = (neighbour(at.checked_sub(1)), neighbour(Some(at)))
1704 && let Some(key) = position_between(before, after)
1705 {
1706 return Ok((key, Vec::new()));
1707 }
1708 let mut keys = Vec::with_capacity(rules.len() + 1);
1710 for _ in 0..=rules.len() {
1711 let key = position_between(keys.last().map(String::as_str), None)
1712 .unwrap_or_else(|| "V".to_owned());
1713 keys.push(key);
1714 }
1715 let key = keys.remove(at);
1716 let renumbered = rules
1717 .iter()
1718 .zip(keys)
1719 .filter(|(rule, key)| rule.position.as_ref() != Some(key))
1720 .map(|(rule, key)| (rule.id, key))
1721 .collect();
1722 Ok((key, renumbered))
1723 }
1724
1725 fn renumbering(
1727 &self,
1728 space: SpaceId,
1729 renumbered: Vec<(EntityId, String)>,
1730 rng: &mut impl CryptoRng,
1731 ) -> Result<Vec<Operation>, NodeError> {
1732 let mut operations = Vec::new();
1733 for (rule, key) in renumbered {
1734 operations.extend(self.replacing(
1735 space,
1736 rule,
1737 vec![(fields::POSITION, Value::Text(key))],
1738 rng,
1739 )?);
1740 }
1741 Ok(operations)
1742 }
1743
1744 pub(crate) fn replacing(
1747 &self,
1748 space: SpaceId,
1749 entity: EntityId,
1750 values: Vec<(FieldName, Value)>,
1751 rng: &mut impl CryptoRng,
1752 ) -> Result<Vec<Operation>, NodeError> {
1753 let state = self.space(space)?.stored.log().state();
1754 let mut operations = Vec::new();
1755 for (field, value) in values {
1756 let current: Vec<StatementId> = state
1757 .current(entity, &field)?
1758 .iter()
1759 .map(|statement| statement.id)
1760 .collect();
1761 let statement = Statement::new(StatementId::random(rng), entity, field, value);
1762 operations.push(Operation::replace(statement, current));
1763 }
1764 Ok(operations)
1765 }
1766}
1767
1768fn checked(
1771 counts: BTreeMap<Option<EntityId>, PolicyCount>,
1772 files: Vec<CheckedFile>,
1773) -> PolicyCheck {
1774 let mut checked: Vec<PolicyCount> = counts.into_values().collect();
1775 checked.sort_by_cached_key(|count| {
1776 (
1777 count.policy.is_none(),
1778 count.name.as_ref().map(|name| name.to_lowercase()),
1779 count.policy,
1780 )
1781 });
1782 PolicyCheck {
1783 policies: checked,
1784 files,
1785 ..PolicyCheck::default()
1786 }
1787}
1788
1789fn tally(
1796 counts: &mut BTreeMap<Option<EntityId>, PolicyCount>,
1797 policies: &Policies,
1798 (choice, file, size): (&Choice, EntityId, Option<u64>),
1799 ((stored, in_place), (disks, away, archived, unchecked)): (
1800 (bool, bool),
1801 (usize, usize, usize, bool),
1802 ),
1803) -> CheckedFile {
1804 let count = counts.entry(choice.policy).or_insert_with(|| PolicyCount {
1805 policy: choice.policy,
1806 name: choice
1807 .policy
1808 .and_then(|id| policies.policies.get(&id))
1809 .and_then(|policy| policy.name.clone()),
1810 needs: choice.needs,
1811 files: 0,
1812 short: 0,
1813 lacking: Vec::new(),
1814 few_copies: 0,
1815 few_away: 0,
1816 few_archived: 0,
1817 unchecked: 0,
1818 none_here: Vec::new(),
1819 not_stored: Vec::new(),
1820 });
1821 count.files += 1;
1822 let lacks = choice.needs.lacks(disks, away, archived);
1823 count.few_copies += usize::from(lacks.copies);
1824 count.few_away += usize::from(lacks.away);
1825 count.few_archived += usize::from(lacks.archived);
1826 count.unchecked += usize::from(unchecked);
1827 if lacks.any() {
1828 count.short += 1;
1829 count.lacking.push(file);
1830 }
1831 if !stored && !in_place {
1832 count.none_here.push(file);
1833 } else if choice.needs.kept == Kept::Store && !stored {
1834 count.not_stored.push(file);
1835 }
1836 CheckedFile {
1837 file,
1838 policy: choice.policy,
1839 size,
1840 disks,
1841 away,
1842 archived,
1843 lacks,
1844 unchecked,
1845 }
1846}
1847
1848#[derive(Clone, Debug)]
1851struct FoundAt {
1852 device: EntityId,
1853 path: String,
1854 modified: Option<Value>,
1855 content: Option<Hash>,
1856 size: Option<u64>,
1857}
1858
1859impl FoundAt {
1860 fn holds(&self, content: Option<Hash>) -> bool {
1864 if self.content.is_none() || self.content != content {
1865 return false;
1866 }
1867 let Ok(metadata) = fs::metadata(&self.path) else {
1868 return false;
1869 };
1870 let modified = metadata.modified().ok().and_then(moment).map(Value::Date);
1871 metadata.is_file()
1872 && self.size == Some(metadata.len())
1873 && modified.is_some()
1874 && modified == self.modified
1875 }
1876}
1877
1878fn places_by_file<S: Statements>(
1882 state: &State<S>,
1883 origins: &[EntityId],
1884 (devices_needed, part): (&BTreeSet<EntityId>, usize),
1885) -> Result<BTreeMap<EntityId, Vec<FoundAt>>, NodeError>
1886where
1887 NodeError: From<S::Error>,
1888{
1889 let mut canonical_devices: BTreeMap<EntityId, EntityId> = BTreeMap::new();
1891 let asked = [
1892 fields::TYPE,
1893 fields::DELETED,
1894 fields::MERGED_INTO,
1895 ORIGIN_OF,
1896 FOUND_ON,
1897 PATH,
1898 MODIFIED,
1899 CONTENT,
1900 SIZE,
1901 ];
1902 let mut seen = BTreeSet::new();
1903 let mut places: BTreeMap<EntityId, Vec<FoundAt>> = BTreeMap::new();
1904 by_parts(state, origins, (&asked, part), &mut |part, origins| {
1905 for &origin in origins {
1906 let origin = part.canonical(origin)?;
1907 if !seen.insert(origin)
1908 || part.is_deleted(origin)?
1909 || !part.types(origin)?.contains(&ORIGIN)
1910 {
1911 continue;
1912 }
1913 let values = |field: &FieldName| -> Result<Vec<Value>, NodeError> {
1914 Ok(part
1915 .current(origin, field)?
1916 .iter()
1917 .map(|statement| statement.value.clone())
1918 .collect())
1919 };
1920 let modified = values(&MODIFIED)?.into_iter().next();
1921 let content = values(&CONTENT)?.into_iter().find_map(|value| match value {
1922 Value::Blob(content) => Some(content),
1923 _ => None,
1924 });
1925 let size = values(&SIZE)?.into_iter().find_map(|value| match value {
1926 Value::Integer(size) => u64::try_from(size).ok(),
1927 _ => None,
1928 });
1929 let mut devices = Vec::new();
1930 for device in values(&FOUND_ON)?.iter().filter_map(Value::as_reference) {
1931 let device = if let Some(canonical) = canonical_devices.get(&device) {
1932 *canonical
1933 } else {
1934 let canonical = canonical_device(state, device)?;
1935 canonical_devices.insert(device, canonical);
1936 canonical
1937 };
1938 devices.push(device);
1939 }
1940 let paths: Vec<String> = values(&PATH)?
1941 .iter()
1942 .filter_map(|path| path.as_text().map(str::to_owned))
1943 .collect();
1944 for file in values(&ORIGIN_OF)?.iter().filter_map(Value::as_reference) {
1945 let found = places.entry(file).or_default();
1946 for device in &devices {
1947 if !devices_needed.contains(device) {
1950 found.push(FoundAt {
1951 device: *device,
1952 path: String::new(),
1953 modified: None,
1954 content: None,
1955 size: None,
1956 });
1957 continue;
1958 }
1959 for path in &paths {
1960 found.push(FoundAt {
1961 device: *device,
1962 path: path.clone(),
1963 modified: modified.clone(),
1964 content,
1965 size,
1966 });
1967 }
1968 }
1969 }
1970 }
1971 Ok(())
1972 })?;
1973 Ok(places)
1974}
1975
1976fn canonical_device<S: Statements>(
1978 state: &State<S>,
1979 device: EntityId,
1980) -> Result<EntityId, NodeError>
1981where
1982 NodeError: From<S::Error>,
1983{
1984 Ok(state.canonical(device)?)
1985}
1986
1987fn facts_of_part(part: &State, file: EntityId) -> Result<Facts, NodeError> {
1989 facts_but_places(part, file)
1990}
1991
1992#[derive(Clone, Debug, Default, PartialEq, Eq)]
1994pub struct PolicyEdit {
1995 pub name: Option<String>,
1997 pub copies: Option<u32>,
1999 pub away: Option<u32>,
2001 pub archived: Option<u32>,
2003 pub kept: Option<Kept>,
2005}
2006
2007pub(crate) fn own_choices<S: Statements>(
2009 state: &State<S>,
2010 entity: EntityId,
2011) -> Result<Vec<EntityId>, NodeError>
2012where
2013 NodeError: From<S::Error>,
2014{
2015 let mut own = Vec::new();
2016 for statement in state.current(entity, &POLICY)? {
2017 if let Some(policy) = statement.value.as_reference() {
2018 own.push(state.canonical(policy)?);
2019 }
2020 }
2021 Ok(own)
2022}
2023
2024#[cfg(test)]
2025mod tests {
2026 use nibkeep_model::storage::Memory;
2027 use nibkeep_std::{CAMERA_MODEL, PHOTO};
2028 use nibkeep_testkit::TestRng;
2029 use nibkeep_time::Timestamp;
2030
2031 use super::*;
2032
2033 #[test]
2034 fn the_strictest_of_competing_values_counts() {
2035 let mut rng = TestRng::new("strictest");
2036 let policy = rng.entity_id();
2037 let text = |text: &str| Value::Text(text.to_owned());
2038 let operations = [
2039 assert(
2040 policy,
2041 fields::TYPE,
2042 text(STORAGE_POLICY.as_str()),
2043 &mut rng,
2044 ),
2045 assert(policy, POLICY_COPIES, Value::Integer(2), &mut rng),
2047 assert(policy, POLICY_COPIES, Value::Integer(3), &mut rng),
2048 assert(policy, POLICY_ARCHIVED, Value::Integer(1), &mut rng),
2049 assert(policy, POLICY_KEPT, text("in-place"), &mut rng),
2050 assert(policy, POLICY_KEPT, text("store"), &mut rng),
2051 ];
2052 let mut state = State::in_storage(Memory::default());
2053 for (at, operation) in (1_000..).zip(&operations) {
2054 let Ok(()) = state.apply(operation, Timestamp::new(at, 0));
2055 }
2056 let policies = Policies::read(&state, [policy], []).expect("reads");
2057 assert_eq!(
2058 policies.policies[&policy].needs,
2059 Needs {
2060 copies: 3,
2061 away: 0,
2062 archived: 1,
2063 kept: Kept::Store,
2064 }
2065 );
2066 }
2067
2068 #[test]
2069 fn every_condition_must_hold() {
2070 let mut rng = TestRng::new("conditions");
2071 let (device, other) = (rng.entity_id(), rng.entity_id());
2072 let facts = Facts {
2073 types: [FILE].into_iter().collect(),
2074 fields: [CAMERA_MAKE].into_iter().collect(),
2075 media_type: Some("video/mp4".to_owned()),
2076 size: Some(100),
2077 places: vec![(device, "/home/ada/Downloads/film.mp4".to_owned())],
2078 };
2079 let folder = |path: &str, device: EntityId| Conditions {
2080 folder: Some(Folder {
2081 path: path.to_owned(),
2082 device,
2083 }),
2084 ..Conditions::default()
2085 };
2086 assert!(Conditions::default().hold(&facts), "no conditions");
2087 assert!(folder("/home/ada/Downloads", device).hold(&facts));
2088 assert!(folder("/home/ada", device).hold(&facts), "below the folder");
2089 assert!(
2090 !folder("/home/ada/Down", device).hold(&facts),
2091 "a folder is named whole"
2092 );
2093 assert!(
2094 !folder("/home/ada/Downloads", other).hold(&facts),
2095 "on another device"
2096 );
2097 let mut elsewhere = facts.clone();
2098 elsewhere
2099 .places
2100 .push((device, "/home/ada/Films/film.mp4".to_owned()));
2101 assert!(
2102 !folder("/home/ada/Downloads", device).hold(&elsewhere),
2103 "found elsewhere too"
2104 );
2105 let media = |prefix: &str| Conditions {
2106 media_type: Some(prefix.to_owned()),
2107 ..Conditions::default()
2108 };
2109 assert!(media("video/").hold(&facts));
2110 assert!(media("video/mp4").hold(&facts));
2111 assert!(!media("image/").hold(&facts));
2112 let larger = |bytes| Conditions {
2113 larger_than: Some(bytes),
2114 ..Conditions::default()
2115 };
2116 assert!(larger(99).hold(&facts));
2117 assert!(!larger(100).hold(&facts));
2118 let of_type = |name| Conditions {
2119 of_type: Some(name),
2120 ..Conditions::default()
2121 };
2122 assert!(of_type(FILE).hold(&facts));
2123 assert!(!of_type(PHOTO).hold(&facts));
2124 let has = |field| Conditions {
2125 has: Some(field),
2126 ..Conditions::default()
2127 };
2128 assert!(has(CAMERA_MAKE).hold(&facts));
2129 assert!(!has(CAMERA_MODEL).hold(&facts));
2130 let all = Conditions {
2132 of_type: Some(FILE),
2133 has: Some(CAMERA_MAKE),
2134 ..media("video/")
2135 };
2136 assert!(all.hold(&facts));
2137 assert!(
2138 !Conditions {
2139 larger_than: Some(100),
2140 ..all
2141 }
2142 .hold(&facts)
2143 );
2144 }
2145
2146 #[test]
2147 fn a_rule_with_a_condition_it_cannot_read_chooses_nothing() {
2148 let mut rng = TestRng::new("unreadable");
2149 let (policy, rule) = (rng.entity_id(), rng.entity_id());
2150 let text = |text: &str| Value::Text(text.to_owned());
2151 let operations = [
2152 assert(
2153 policy,
2154 fields::TYPE,
2155 text(STORAGE_POLICY.as_str()),
2156 &mut rng,
2157 ),
2158 assert(rule, fields::TYPE, text(STORAGE_RULE.as_str()), &mut rng),
2159 assert(rule, RULE_POLICY, Value::Reference(policy), &mut rng),
2160 assert(rule, RULE_TYPE, text("not a type name"), &mut rng),
2161 ];
2162 let mut state = State::in_storage(Memory::default());
2163 for (at, operation) in (1_000..).zip(&operations) {
2164 let Ok(()) = state.apply(operation, Timestamp::new(at, 0));
2165 }
2166 let policies = Policies::read(&state, [policy], [rule]).expect("reads");
2167 assert_eq!(policies.rules[0].policy, None);
2168 let choice = policies.choose(&[], &Facts::default());
2169 assert_eq!(choice.by, ChosenBy::Fallback);
2170 }
2171
2172 fn library(name: &str, rng: &mut TestRng) -> (std::path::PathBuf, Library) {
2175 let directory = nibkeep_testkit::empty_directory(
2176 std::env::temp_dir(),
2177 &format!("nibkeep-policies-{name}-{}", std::process::id()),
2178 );
2179 let protection = nibkeep_keys::NewProtection::Passphrase(
2180 "correct horse",
2181 nibkeep_crypto::PassphraseParams::new(64, 1, 1).expect("valid"),
2182 );
2183 let library = Library::create(
2184 &directory,
2185 &crate::NewLibrary::new("Ada", "laptop", "nib"),
2186 &protection,
2187 NOW,
2188 rng,
2189 )
2190 .expect("creates");
2191 (directory, library)
2192 }
2193
2194 const NOW: u64 = 1_790_000_000_000;
2195
2196 fn set_position(library: &mut Library, rule: EntityId, key: &str, rng: &mut TestRng) {
2198 let space = library.personal_space();
2199 let operations = library
2200 .replacing(
2201 space,
2202 rule,
2203 vec![(fields::POSITION, Value::Text(key.to_owned()))],
2204 rng,
2205 )
2206 .expect("reads");
2207 library
2208 .commit(space, operations, NOW, rng)
2209 .expect("commits");
2210 }
2211
2212 #[test]
2213 fn a_rule_goes_where_it_is_put_when_keys_are_shared_or_bad() {
2214 let mut rng = TestRng::new("placing");
2215 let (directory, mut library) = library("placing", &mut rng);
2216 let space = library.personal_space();
2217 library
2218 .install_policies(space, None, NOW, &mut rng)
2219 .expect("installs");
2220 let rules = library.rules(space).expect("reads");
2221 let (camera, rest) = (rules[0].id, rules[1].id);
2222 let standard = derived(space, STANDARD);
2223 let key = rules[0].position.clone().expect("a key");
2225 set_position(&mut library, rest, &key, &mut rng);
2226 let order = |library: &Library| -> Vec<EntityId> {
2227 library
2228 .rules(space)
2229 .expect("reads")
2230 .iter()
2231 .map(|rule| rule.id)
2232 .collect()
2233 };
2234 let first_two = order(&library);
2235 let new = library
2236 .add_rule(
2237 space,
2238 &NewRule::new(standard),
2239 Place::After(first_two[0]),
2240 NOW,
2241 &mut rng,
2242 )
2243 .expect("adds");
2244 assert_eq!(order(&library), [first_two[0], new, first_two[1]]);
2245 set_position(&mut library, camera, "not a key!", &mut rng);
2247 assert_eq!(order(&library).last(), Some(&camera));
2248 let last = library
2249 .add_rule(space, &NewRule::new(standard), Place::Last, NOW, &mut rng)
2250 .expect("adds");
2251 assert_eq!(order(&library).last(), Some(&last));
2252 assert_eq!(order(&library).len(), 4);
2253 drop(library);
2254 let _ = std::fs::remove_dir_all(directory);
2255 }
2256
2257 #[test]
2258 fn the_position_written_last_counts() {
2259 for (earlier, later) in [("a", "b"), ("b", "a")] {
2261 let mut rng = TestRng::new(&format!("last position {earlier}"));
2262 let (rule, policy) = (rng.entity_id(), rng.entity_id());
2263 let text = |text: &str| Value::Text(text.to_owned());
2264 let operations = [
2265 assert(
2266 policy,
2267 fields::TYPE,
2268 text(STORAGE_POLICY.as_str()),
2269 &mut rng,
2270 ),
2271 assert(rule, fields::TYPE, text(STORAGE_RULE.as_str()), &mut rng),
2272 assert(rule, RULE_POLICY, Value::Reference(policy), &mut rng),
2273 assert(rule, fields::POSITION, text(earlier), &mut rng),
2275 assert(rule, fields::POSITION, text(later), &mut rng),
2276 ];
2277 let mut state = State::in_storage(Memory::default());
2278 for (at, operation) in (1_000..).zip(&operations) {
2279 let Ok(()) = state.apply(operation, Timestamp::new(at, 0));
2280 }
2281 let policies = Policies::read(&state, [policy], [rule]).expect("reads");
2282 assert_eq!(policies.rules[0].position.as_deref(), Some(later));
2283 }
2284 }
2285
2286 #[test]
2287 fn policies_checked_in_parts_are_checked_as_at_once() {
2288 let mut rng = TestRng::new("checked in parts");
2289 let (directory, mut library) = library("checked-in-parts", &mut rng);
2290 let space = library.personal_space();
2291 let downloads = directory.join("downloads");
2292 let elsewhere = directory.join("elsewhere");
2293 std::fs::create_dir_all(&downloads).expect("makes a folder");
2294 std::fs::create_dir_all(&elsewhere).expect("makes a folder");
2295 library
2296 .install_policies(space, Some(&downloads), NOW, &mut rng)
2297 .expect("installs");
2298 let mut added = Vec::new();
2299 for n in 0..12 {
2300 let folder = if n % 2 == 0 { &downloads } else { &elsewhere };
2301 let path = folder.join(format!("file {n}"));
2302 std::fs::write(&path, format!("the content of file {n}")).expect("writes");
2303 added.push((
2304 path.clone(),
2305 library.add_file(space, &path, NOW, &mut rng).expect("adds"),
2306 ));
2307 }
2308 std::fs::write(&added[0].0, b"changed by another app").expect("writes");
2310 library
2311 .merge_entities(space, added[2].1.file, added[3].1.file, NOW, &mut rng)
2312 .expect("merges");
2313 let critical = derived(space, CRITICAL);
2314 library
2315 .set_policy(space, added[4].1.file, Some(critical), NOW, &mut rng)
2316 .expect("sets");
2317 let in_parts = library
2318 .check_policies_in_parts(space, (2, false), NOW)
2319 .expect("checks");
2320 let at_once = library
2321 .check_policies_in_parts(space, (100_000, false), NOW)
2322 .expect("checks");
2323 assert_eq!(in_parts, at_once);
2324 let open = library.space(space).expect("a space");
2326 let state = open.stored.log().state();
2327 let policies = library.read_policies(space).expect("reads");
2328 let mut counts = BTreeMap::new();
2329 let files: BTreeSet<EntityId> = added
2330 .iter()
2331 .map(|(_, added)| state.canonical(added.file).expect("reads"))
2332 .collect();
2333 for file in files {
2334 let choice = library.policy_of(space, file).expect("chooses");
2335 let content = state
2336 .current(file, &CONTENT)
2337 .expect("reads")
2338 .iter()
2339 .find_map(|statement| match statement.value {
2340 Value::Blob(hash) => Some(hash),
2341 _ => None,
2342 });
2343 let stored = content.is_some_and(|content| open.stored.holds_ordinary_blob(&content));
2344 let mut in_place = false;
2345 for (origin, device, path) in origins_of(state, file).expect("reads") {
2346 let first = |field: &FieldName| {
2347 state
2348 .current(origin, field)
2349 .expect("reads")
2350 .first()
2351 .map(|statement| statement.value.clone())
2352 };
2353 let place = FoundAt {
2354 device,
2355 path,
2356 modified: first(&MODIFIED),
2357 content: match first(&CONTENT) {
2358 Some(Value::Blob(content)) => Some(content),
2359 _ => None,
2360 },
2361 size: match first(&SIZE) {
2362 Some(Value::Integer(size)) => u64::try_from(size).ok(),
2363 _ => None,
2364 },
2365 };
2366 in_place |= device == library.info.device && place.holds(content);
2367 }
2368 let disks = (usize::from(stored || in_place), 0, 0, false);
2370 tally(
2371 &mut counts,
2372 &policies,
2373 (&choice, file, None),
2374 ((stored, in_place), disks),
2375 );
2376 }
2377 assert_eq!(in_parts.policies, checked(counts, Vec::new()).policies);
2378 let files: usize = at_once.policies.iter().map(|count| count.files).sum();
2379 assert_eq!(files, 11, "twelve files, two of them merged");
2380 assert!(
2381 at_once
2382 .policies
2383 .iter()
2384 .any(|count| count.none_here.contains(&added[0].1.file)),
2385 "the changed one has no copy here"
2386 );
2387 drop(library);
2388 let _ = std::fs::remove_dir_all(directory);
2389 }
2390}