Skip to main content

nibkeep_node/library/
policies.rs

1//! Storage policies: how many copies the files of a space need, where, and whether this
2//! device keeps them in NibKeep's store or where they are, and the rules that choose a
3//! file's policy ([technical design: storage policies]).
4//!
5//! [technical design: storage policies]: ../../../../docs/Technical-design.md#93-storage-policies
6
7use 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
29/// The type of storage policies.
30pub const STORAGE_POLICY: TypeName = TypeName::from_static("org.nibkeep.storage-policy");
31
32/// The type of the rules that choose a file's policy.
33pub const STORAGE_RULE: TypeName = TypeName::from_static("org.nibkeep.storage-rule");
34
35/// A file's own choice of policy: a reference to it.
36pub const POLICY: FieldName = FieldName::from_static("org.nibkeep.policy");
37
38/// How many copies the data of a policy needs, as an integer.
39pub(crate) const POLICY_COPIES: FieldName = FieldName::from_static("org.nibkeep.policy-copies");
40
41/// How many of the copies are outside the home, as an integer.
42pub(crate) const POLICY_AWAY: FieldName = FieldName::from_static("org.nibkeep.policy-away");
43
44/// How many of the copies are on archive nodes, as an integer.
45pub(crate) const POLICY_ARCHIVED: FieldName = FieldName::from_static("org.nibkeep.policy-archived");
46
47/// Where devices keep the data of a policy: `store` or `in-place`.
48pub(crate) const POLICY_KEPT: FieldName = FieldName::from_static("org.nibkeep.policy-kept");
49
50/// The policy that a rule chooses: a reference to it.
51pub(crate) const RULE_POLICY: FieldName = FieldName::from_static("org.nibkeep.rule-policy");
52
53/// A condition of a rule: the file has this type, as text.
54pub(crate) const RULE_TYPE: FieldName = FieldName::from_static("org.nibkeep.rule-type");
55
56/// A condition of a rule: the file has a value of this field, as text.
57pub(crate) const RULE_HAS: FieldName = FieldName::from_static("org.nibkeep.rule-has");
58
59/// A condition of a rule, with [`RULE_DEVICE`]: every place the file was found is in this
60/// folder or below it, as text, on that device.
61pub(crate) const RULE_FOLDER: FieldName = FieldName::from_static("org.nibkeep.rule-folder");
62
63/// The device whose folder [`RULE_FOLDER`] names: a reference to it.
64pub(crate) const RULE_DEVICE: FieldName = FieldName::from_static("org.nibkeep.rule-device");
65
66/// A condition of a rule: the file's media type is this one or starts with it, as text.
67pub(crate) const RULE_MEDIA_TYPE: FieldName = FieldName::from_static("org.nibkeep.rule-media-type");
68
69/// A condition of a rule: the file is larger than this many bytes, as an integer.
70pub(crate) const RULE_LARGER_THAN: FieldName =
71	FieldName::from_static("org.nibkeep.rule-larger-than");
72
73/// Not a condition: adding a file larger than this many bytes, as an integer, that the rule
74/// chooses for asks whether it can be got again.
75pub(crate) const RULE_ASKS_ABOVE: FieldName = FieldName::from_static("org.nibkeep.rule-asks-above");
76
77/// The fields of policies and rules, and a file's own choice, which only the engine's
78/// policy functions write.
79const 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
95/// Whether a field is one of those of policies and rules, which only the policy functions
96/// write.
97pub(crate) fn is_own_field(field: &FieldName) -> bool {
98	OWN_FIELDS.contains(field) || super::backups::is_own_field(field)
99}
100
101/// Whether a type is one of those of policies and rules, whose entities only the policy
102/// functions make.
103pub(crate) fn is_own_type(name: &TypeName) -> bool {
104	*name == STORAGE_POLICY || *name == STORAGE_RULE || *name == super::backups::BACKUP
105}
106
107/// The definitions of the types of policies and rules, which NibKeep defines in code.
108pub(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/// Where devices keep the files of a policy. The store is the stricter.
132#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
133pub enum Kept {
134	/// Where the file already is: NibKeep records where, and its hash.
135	InPlace,
136	/// In NibKeep's store, sealed.
137	Store,
138}
139
140impl Kept {
141	/// The text that stands for it.
142	#[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/// What a policy asks of the copies of a file.
152#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
153pub struct Needs {
154	/// How many copies, at least 1.
155	pub copies: u32,
156	/// How many of them outside the home.
157	pub away: u32,
158	/// How many of them on archive nodes.
159	pub archived: u32,
160	/// Where devices keep them.
161	pub kept: Kept,
162}
163
164impl Needs {
165	/// What the Critical policy asks by default: three copies, one of them away from home,
166	/// in the store; the space's changes count against it where it is gone.
167	pub const CRITICAL: Self = Self {
168		copies: 3,
169		away: 1,
170		archived: 0,
171		kept: Kept::Store,
172	};
173
174	/// One copy, in the store: what a content needs that no file holds, as a thumbnail's,
175	/// when a device that drops its space removes its copy, as every replica keeps it.
176	pub const ONE: Self = Self {
177		copies: 1,
178		away: 0,
179		archived: 0,
180		kept: Kept::Store,
181	};
182
183	/// What a file needs when no policy is chosen for it: two copies, one of them on an
184	/// archive node, in the store, as Standard asks.
185	pub const FALLBACK: Self = Self {
186		copies: 2,
187		away: 0,
188		archived: 1,
189		kept: Kept::Store,
190	};
191
192	/// What a file lacks of this that has copies that count on `disks` disks, `away` of
193	/// them away from home and `archived` of them archive nodes'.
194	#[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	/// What a file lacks of this whose copies are `copies`, as [`Library::copies_of`] gives
205	/// them: those that count, by their disks' marks.
206	#[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	/// The strictest of two: the most copies of each kind, and the store over in place.
217	#[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/// What the copies of a file lack of what its policy needs.
229#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
230pub struct Lacks {
231	/// It is on fewer disks than the policy needs.
232	pub copies: bool,
233	/// Fewer of its copies are away from home than the policy needs.
234	pub away: bool,
235	/// Fewer of its copies are on archive nodes than the policy needs.
236	pub archived: bool,
237}
238
239impl Lacks {
240	/// Whether it lacks anything.
241	#[must_use]
242	pub fn any(self) -> bool {
243		self.copies || self.away || self.archived
244	}
245}
246
247/// A storage policy of a space.
248#[derive(Clone, Debug, PartialEq, Eq)]
249pub struct Policy {
250	/// Its entity.
251	pub id: EntityId,
252	/// Its name, if it has one.
253	pub name: Option<String>,
254	/// What it asks, the strictest of its values where they compete.
255	pub needs: Needs,
256}
257
258/// A folder on a device, which a rule names.
259#[derive(Clone, Debug, PartialEq, Eq)]
260pub struct Folder {
261	/// The folder, as the device's file system resolves it.
262	pub path: String,
263	/// The device.
264	pub device: EntityId,
265}
266
267/// The conditions of a rule, which must all hold for it to choose. A rule without any
268/// chooses for every file.
269#[derive(Clone, Debug, Default, PartialEq, Eq)]
270pub struct Conditions {
271	/// The file has this type.
272	pub of_type: Option<TypeName>,
273	/// The file has a value of this field.
274	pub has: Option<FieldName>,
275	/// Every place the file was found is in this folder, or below it, on its device.
276	pub folder: Option<Folder>,
277	/// The file's media type is this one, or starts with it.
278	pub media_type: Option<String>,
279	/// The file is larger than this many bytes.
280	pub larger_than: Option<u64>,
281}
282
283impl Conditions {
284	/// Whether the rule has no conditions, and so chooses for every file.
285	#[must_use]
286	pub fn is_empty(&self) -> bool {
287		*self == Self::default()
288	}
289
290	/// Whether every condition holds for a file.
291	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/// A rule of a space, which chooses a policy for the files that it holds for.
318#[derive(Clone, Debug, PartialEq, Eq)]
319pub struct Rule {
320	/// Its entity.
321	pub id: EntityId,
322	/// The policy it chooses, if it names one that is not deleted.
323	pub policy: Option<EntityId>,
324	/// Its conditions.
325	pub conditions: Conditions,
326	/// Adding a file larger than this many bytes that the rule chooses for asks whether the
327	/// file can be got again.
328	pub asks_above: Option<u64>,
329	/// Its position key, if it has a valid one.
330	position: Option<String>,
331}
332
333/// A rule to add.
334#[derive(Clone, Debug, PartialEq, Eq)]
335pub struct NewRule {
336	/// The policy it chooses.
337	pub policy: EntityId,
338	/// The file has this type.
339	pub of_type: Option<TypeName>,
340	/// The file has a value of this field.
341	pub has: Option<FieldName>,
342	/// Every place the file was found is in this folder on this device, or below it.
343	pub folder: Option<std::path::PathBuf>,
344	/// The file's media type is this one, or starts with it.
345	pub media_type: Option<String>,
346	/// The file is larger than this many bytes.
347	pub larger_than: Option<u64>,
348	/// Adding a larger file that the rule chooses for asks whether it can be got again.
349	pub asks_above: Option<u64>,
350}
351
352impl NewRule {
353	/// A rule that chooses `policy` for every file.
354	#[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/// Where a rule goes among the rules of a space.
369#[derive(Clone, Copy, Debug, PartialEq, Eq)]
370pub enum Place {
371	/// Before every other rule, where it wins over them.
372	First,
373	/// After every other rule.
374	Last,
375	/// Just before this rule.
376	Before(EntityId),
377	/// Just after this rule.
378	After(EntityId),
379	/// Before the rule without conditions at the end, which chooses for every other file,
380	/// if there is one, or else last.
381	BeforeTheRest,
382}
383
384/// What chose a file's policy.
385#[derive(Clone, Copy, Debug, PartialEq, Eq)]
386pub enum ChosenBy {
387	/// The file's own choice.
388	Own,
389	/// This rule, the first whose conditions held.
390	Rule(EntityId),
391	/// Nothing: no rule held, and the file needs what [`Needs::FALLBACK`] says.
392	Fallback,
393}
394
395/// The policy chosen for a file.
396#[derive(Clone, Debug, PartialEq, Eq)]
397pub struct Choice {
398	/// The policy, unless none was chosen.
399	pub policy: Option<EntityId>,
400	/// What the file needs.
401	pub needs: Needs,
402	/// What chose it.
403	pub by: ChosenBy,
404	/// Adding a file larger than this many bytes asks whether it can be got again, as the
405	/// rule that chose says.
406	pub asks_above: Option<u64>,
407}
408
409/// How a policy is met for the files it is chosen for.
410#[derive(Clone, Debug, PartialEq, Eq)]
411pub struct PolicyCount {
412	/// The policy, or `None` for the files that no rule chooses for.
413	pub policy: Option<EntityId>,
414	/// Its name, if it has one.
415	pub name: Option<String>,
416	/// What it asks.
417	pub needs: Needs,
418	/// The files it is chosen for.
419	pub files: usize,
420	/// Those that lack copies: every file with fewer disks than the policy needs, or fewer
421	/// of them away from home or on archive nodes.
422	pub short: usize,
423	/// Which they are, for an app to list.
424	pub lacking: Vec<EntityId>,
425	/// Those on fewer disks than the policy needs.
426	pub few_copies: usize,
427	/// Those with fewer copies away from home than the policy needs.
428	pub few_away: usize,
429	/// Those with fewer copies on archive nodes than the policy needs.
430	pub few_archived: usize,
431	/// Those with a copy that does not count, as it was last checked more than 8 weeks ago
432	/// ([technical design: checking and repair]).
433	///
434	/// [technical design: checking and repair]: ../../../../docs/Technical-design.md#97-checking-and-repair
435	pub unchecked: usize,
436	/// Those of which this device holds no copy at all: not in the store, and not where they
437	/// were found, unchanged.
438	pub none_here: Vec<EntityId>,
439	/// Those that the policy keeps in the store, which this device holds only where they
440	/// are.
441	pub not_stored: Vec<EntityId>,
442}
443
444/// What a policy needs, in policy check order, and the files that do not meet it, with
445/// copies counted by disk across devices ([technical design: where the copies are]).
446///
447/// [technical design: where the copies are]: ../../../../docs/Technical-design.md#96-where-the-copies-are
448#[derive(Clone, Debug, Default, PartialEq, Eq)]
449pub struct PolicyCheck {
450	/// Each policy that a file is chosen for, by name, and the files that no rule chooses
451	/// for last.
452	pub policies: Vec<PolicyCount>,
453	/// The disks that hold copies, this replica's first, as their replicas' accounts say.
454	pub disks: Vec<super::accounts::Disk>,
455	/// How the space's changes are held.
456	pub changes: super::accounts::ChangeCopies,
457	/// Each file counted, in the order checked: how its copies meet its policy, for an app
458	/// to list them all.
459	pub files: Vec<CheckedFile>,
460}
461
462/// How the copies of a file meet the policy chosen for it, as [`Library::check_policies`]
463/// counts them.
464#[derive(Clone, Debug, PartialEq, Eq)]
465pub struct CheckedFile {
466	/// The file.
467	pub file: EntityId,
468	/// The policy chosen for it, or `None` if no rule chooses one.
469	pub policy: Option<EntityId>,
470	/// Its size in bytes, as it records it.
471	pub size: Option<u64>,
472	/// The disks whose copies of it count.
473	pub disks: usize,
474	/// How many of them are away from home.
475	pub away: usize,
476	/// How many of them are archive nodes'.
477	pub archived: usize,
478	/// What its copies lack of its policy.
479	pub lacks: Lacks,
480	/// Whether a disk holds a copy of it that does not count, as it was last checked more
481	/// than 8 weeks ago.
482	pub unchecked: bool,
483}
484
485/// What rules look at in a file.
486#[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	/// The places it was found: each device and path.
493	pub(crate) places: Vec<(EntityId, String)>,
494}
495
496/// The policies and rules of a space, read once for many choices.
497pub(crate) struct Policies {
498	policies: BTreeMap<EntityId, Policy>,
499	rules: Vec<Rule>,
500}
501
502impl Policies {
503	/// Reads the policies and rules of a space's state.
504	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	/// The policy chosen for a file, whose own choices are `own`.
543	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	/// Whether a rule asks about files of this size: whether any rule asks above a smaller
573	/// one.
574	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	/// Whether the space has this policy, not deleted.
581	pub(crate) fn has_policy(&self, id: EntityId) -> bool {
582		self.policies.contains_key(&id)
583	}
584
585	/// Whether the space has this rule, not deleted.
586	pub(crate) fn has_rule(&self, id: EntityId) -> bool {
587		self.rules.iter().any(|rule| rule.id == id)
588	}
589
590	/// The strictest of these policies that are not deleted, if any is.
591	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	/// The fields that rules ask a file to have a value of.
598	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
606/// Reads a policy, the strictest of its values where they compete. A policy that says
607/// nothing of a number needs none of it, and one copy at least; one that does not say
608/// where its files are kept keeps them in the store.
609fn 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
646/// Reads a rule. Where a field has competing values, the rule takes the first by ID, and
647/// the strictest of the policies it names.
648fn 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	// A condition that is there but cannot be read holds for no file, so the rule chooses
699	// nothing, rather than for every file, as if it had no such condition.
700	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
721/// A rule's position key, if it has a valid one: the one written last, as in ordered lists.
722fn 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
741/// The name an entity shows first, by ID among competing ones.
742pub(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
756/// What rules look at in a file of a state: its types, fields, media type and size, and
757/// the places its origins say it was found, of those that are not deleted.
758pub(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
770/// What rules look at in a file of a state, but the places it was found.
771fn 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
789/// The size of a file of a state, as it was recorded.
790pub(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
806/// Whether a record of where a file's plain copy is, an origin or a checkout, stands in a
807/// state: neither deleted nor moved to another space with its file, which records it then.
808pub(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
818/// The origins of a file of a state that stand there, neither deleted nor moved with the
819/// file, each with the device and the path it says the file was found on.
820pub(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
853/// An entity ID that a space's default policies and rules take, derived from the space's ID
854/// and `label`, so that devices that install them at once install the same entities.
855fn 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
860/// The default policies of a space, by label.
861const CRITICAL: &str = "critical";
862const STANDARD: &str = "standard";
863const REPLACEABLE: &str = "replaceable";
864
865/// The default rules of a space, by label; a device's rule for its downloads folder adds
866/// the device's ID to its label.
867const FROM_A_CAMERA: &str = "from a camera";
868const ANY_OTHER: &str = "any other file";
869const DOWNLOADS: &str = "downloads";
870
871/// The size above which the rule for any other file asks whether a file can be got again:
872/// 1 GiB.
873const ASKS_ABOVE: u64 = 1 << 30;
874
875/// The IDs of a space's default policies, Critical, Standard and Replaceable, in that
876/// order, whether or not they are installed.
877pub(crate) fn default_policies(space: SpaceId) -> [EntityId; 3] {
878	[CRITICAL, STANDARD, REPLACEABLE].map(|label| derived(space, label))
879}
880
881/// The default policy that the answer about a large file chooses for its folder:
882/// Replaceable if the file can be got again, and Standard if not.
883pub(crate) fn answer_policy(space: SpaceId, again: bool) -> EntityId {
884	derived(space, if again { REPLACEABLE } else { STANDARD })
885}
886
887/// An operation that asserts a statement.
888pub(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
902/// The operations that make a policy.
903fn 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
944/// The operations that make a rule, at `position`, with its conditions; a folder is on
945/// `device`.
946fn 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
1012/// A folder as the file system resolves it, so that it compares with the paths where files
1013/// were found.
1014fn 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	/// Gives a space the default policies and rules, if it never had them, and this device
1030	/// a rule for its downloads folder, `downloads`, if it never had one ([technical design:
1031	/// storage policies]): Critical, Standard and Replaceable, and rules that choose Standard for a file
1032	/// from a camera, Replaceable for one from the downloads folder, and Standard for any
1033	/// other, asking above 1 GiB.
1034	///
1035	/// [technical design: storage policies]: ../../../../docs/Technical-design.md#93-storage-policies
1036	///
1037	/// # Errors
1038	///
1039	/// Returns an error if the library has no such space, or the change cannot be saved.
1040	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			// A space with a policy, such as one an import brought, has what it needs.
1057			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				// Between the two rules just made.
1114				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	/// The policies and rules of a space, as they are now.
1133	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	/// The policies of a space that are not deleted, ordered by name without regard to case.
1144	///
1145	/// # Errors
1146	///
1147	/// Returns an error if the library has no such space, or the space cannot be read.
1148	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	/// The rules of a space that are not deleted, in the order in which they choose.
1160	///
1161	/// # Errors
1162	///
1163	/// Returns an error if the library has no such space, or the space cannot be read.
1164	pub fn rules(&self, space: SpaceId) -> Result<Vec<Rule>, NodeError> {
1165		Ok(self.read_policies(space)?.rules)
1166	}
1167
1168	/// The policy of a space that `reference` names: its name, without regard to case, its
1169	/// ID, or a prefix of its ID of at least six characters.
1170	///
1171	/// # Errors
1172	///
1173	/// Returns [`NodeError::NoEntity`] if no policy is named so, [`NodeError::Ambiguous`] if
1174	/// several are, and an error if the space cannot be read.
1175	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	/// Adds a policy to a space.
1211	///
1212	/// # Errors
1213	///
1214	/// Returns [`NodeError::EmptyName`] if the name is empty, and an error if the library
1215	/// has no such space, or the change cannot be saved.
1216	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	/// Changes a policy of a space: each value given replaces the values the policy has of
1243	/// it.
1244	///
1245	/// # Errors
1246	///
1247	/// Returns [`NodeError::NoEntity`] if `policy` is no policy of the space,
1248	/// [`NodeError::EmptyName`] if the name is empty, and an error if the change cannot be
1249	/// saved.
1250	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	/// Adds a rule to a space, at `place` among its rules. A folder is on this device.
1290	///
1291	/// # Errors
1292	///
1293	/// Returns [`NodeError::NoEntity`] if the rule's policy is no policy of the space,
1294	/// [`NodeError::Unreadable`] if its folder is not one, and an error if the change cannot
1295	/// be saved.
1296	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	/// Removes a rule of a space: deletes it, so that it chooses nothing until it is
1322	/// restored.
1323	///
1324	/// # Errors
1325	///
1326	/// Returns [`NodeError::NoEntity`] if `rule` is no rule of the space, and an error if
1327	/// the change cannot be saved.
1328	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	/// Removes a policy of a space: deletes it, so that rules that choose it choose nothing,
1341	/// and files that chose it have their policy chosen by the rules, until it is restored.
1342	///
1343	/// # Errors
1344	///
1345	/// Returns [`NodeError::NoEntity`] if `policy` is no policy of the space, and an error if
1346	/// the change cannot be saved.
1347	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	/// Moves a rule of a space to `place` among the others.
1360	///
1361	/// # Errors
1362	///
1363	/// Returns [`NodeError::NoEntity`] if `rule` is no rule of the space, and an error if
1364	/// the change cannot be saved.
1365	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	/// Sets an entity's own choice of policy, which wins over the rules, or clears it with
1384	/// `None`, so that the rules choose again.
1385	///
1386	/// # Errors
1387	///
1388	/// Returns [`NodeError::NoEntity`] if `policy` is no policy of the space, and an error
1389	/// if the change cannot be saved.
1390	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	/// The policy chosen for an entity of a space, as its own choice or the rules choose.
1423	///
1424	/// # Errors
1425	///
1426	/// Returns an error if the library has no such space, or the space cannot be read.
1427	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	/// How the policies of a space are met for its files, as of `wall_millis`: for each
1437	/// policy, how many files it is chosen for, and which of them lack copies; the disks that
1438	/// hold copies; and how the space's changes are held. Copies count disks: this device's
1439	/// are on its disk, as it holds them now, in the store, where they were found, unchanged,
1440	/// and as unchanged copies of checkouts of their current content; the other devices' are
1441	/// on theirs, as their accounts last said ([technical design: where the copies are]). A
1442	/// copy counts only if it was checked in the 8 weeks before `wall_millis`
1443	/// ([technical design: checking and repair]).
1444	///
1445	/// [technical design: where the copies are]: ../../../../docs/Technical-design.md#96-where-the-copies-are
1446	/// [technical design: checking and repair]: ../../../../docs/Technical-design.md#97-checking-and-repair
1447	///
1448	/// # Errors
1449	///
1450	/// Returns an error if the library has no such space, or the space cannot be read.
1451	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	/// How the policies of a space would be met without this replica's disk, for the files
1460	/// whose copies this disk holds, sealed or where they are: as a drop of the space would
1461	/// leave them ([technical design: devices that choose their spaces]).
1462	///
1463	/// [technical design: devices that choose their spaces]: ../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces
1464	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	/// What a space's Critical policy asks, which its changes are counted against.
1475	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	/// Checks the policies of a space as [`Library::check_policies`] does, reading the space
1484	/// part by part, `part` entities at a time: first where its files were found, which
1485	/// their origins say, in short, then the files, with the fields that rules look at. With
1486	/// `without_own`, it counts only the files whose copies this replica's disk holds, as
1487	/// though it did not.
1488	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		// Places are kept in full on this device, and on those that folder rules name.
1504		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					// Where the file, or any merged into it, was found.
1543					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	/// The originals of a space's files on this device, each with its place and the content
1598	/// and size its origin recorded.
1599	///
1600	/// # Errors
1601	///
1602	/// Returns an error if the space cannot be read.
1603	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		// Those that moved with their file are the other space's.
1610		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	/// Returns [`NodeError::NoEntity`] unless `policy` is a policy of the space that is not
1641	/// deleted.
1642	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	/// Returns [`NodeError::NoEntity`] unless `rule` is a rule of the space that is not
1651	/// deleted.
1652	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	/// The position key for a rule at `place`, among the rules but `moving`, and the rules
1666	/// that need new keys for it to fit there: none, unless the rules on either side share a
1667	/// key, or one of them has no valid key, when every rule gets a new one, in its order.
1668	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		// Where the rule goes: before the rule at this index, or last.
1687		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		// No key fits between: every rule gets a new one, in order, the new one at its place.
1709		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	/// The operations that give rules new position keys.
1726	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	/// The operations that set fields of an entity: each value replaces the current values
1745	/// of its field.
1746	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
1768/// The policies counted, in the order of a check: by name, and the files that no rule
1769/// chooses for last.
1770fn 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
1789/// Counts a file under the policy chosen for it, `choice`: whether it lacks copies, by the
1790/// disks whose copies count, how many of them are away and archive nodes', and whether a
1791/// disk holds a copy that does not count, `unchecked`; whether this device holds none; or
1792/// holds it only where it was found though its policy keeps it in the store, by whether the
1793/// device holds it in the store, `stored`, or where it was found, unchanged, `in_place`.
1794/// Returns the file as counted, with its size.
1795fn 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/// Where a file was found, as an origin says, in short: on which device, at which path, when
1849/// it last changed there, and the content and size found there, if the origin says.
1850#[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	/// Whether the file is there still, unchanged, as the version `content`: with the
1861	/// content, size and modification time its origin recorded, as adding a file tells an
1862	/// unchanged one.
1863	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
1878/// Where the files of a state were found, by the file each origin names, read from the
1879/// origins, `origins`, part by part: what an origin says of its file, in short, sits in
1880/// memory, and the origins themselves a part at a time.
1881fn 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	// Devices merged into others are those others, as for a single file; devices are few.
1890	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					// A place on a device that neither is this one nor has a folder rule
1948					// counts only as somewhere else: by its device alone.
1949					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
1976/// The canonical entity of a device of a state.
1977fn 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
1987/// What rules look at in a file of a part of a state, but the places it was found.
1988fn facts_of_part(part: &State, file: EntityId) -> Result<Facts, NodeError> {
1989	facts_but_places(part, file)
1990}
1991
1992/// Changes to a policy: each value given replaces what the policy has.
1993#[derive(Clone, Debug, Default, PartialEq, Eq)]
1994pub struct PolicyEdit {
1995	/// Its name.
1996	pub name: Option<String>,
1997	/// How many copies, at least 1.
1998	pub copies: Option<u32>,
1999	/// How many of them outside the home.
2000	pub away: Option<u32>,
2001	/// How many of them on archive nodes.
2002	pub archived: Option<u32>,
2003	/// Where devices keep them.
2004	pub kept: Option<Kept>,
2005}
2006
2007/// The policies an entity of a state chooses itself.
2008pub(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			// Two devices set each field at once, neither seeing the other.
2046			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		// All of them at once.
2131		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	/// A library in a directory of its own, protected by a quick passphrase, and the
2173	/// directory.
2174	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	/// Sets a rule's position key, as another device could.
2197	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		// Two rules with one key, as two devices that add rules at once can leave them.
2224		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		// A rule with a key that is not one sorts last, and a rule put last goes after it.
2246		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		// In both orders, so that the statements' IDs cannot decide.
2260		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				// Two devices move the rule at once; the later move counts.
2274				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		// One kept where it is changes, two are merged, and one has a policy of its own.
2309		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		// The same as each file's policy and copies, found one file at a time.
2325		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			// One device, unmarked: what it holds is on its one disk.
2369			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}