Skip to main content

nibkeep_node/library/
planner.rs

1//! What a replica keeps of its spaces' sealed blobs, and so asks for in each sync: by its
2//! device's role, size and pins, and when its files were last opened on the device
3//! ([technical design: the planner]).
4//!
5//! [technical design: the planner]: ../../../../docs/Technical-design.md#99-the-planner
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
10use nibkeep_crypto::rand_core::CryptoRng;
11use nibkeep_governance::{DEVICE, PINNED};
12use nibkeep_log::DeviceRole;
13use nibkeep_model::storage::Statements;
14use nibkeep_model::{Operation, State, Statement, Value, fields};
15use nibkeep_std::{CONTENT, FILE, IN_TREE, ON_DEVICE, ROOT_OF, TAKEN, TREE_ROOT};
16use nibkeep_time::{Day, Start};
17
18use super::Library;
19use super::policies::{Kept, facts_of, own_choices, size_of};
20use crate::{NodeError, place};
21
22/// What an everyday computer keeps without a size set: this share of its disk's size, a
23/// tenth.
24const SHARE_OF_DISK: u64 = 10;
25
26/// How long a file opened on this device is kept whatever the size: 10 minutes, so that
27/// opening it fetches it.
28pub(crate) const OPENED_FOR: u64 = 600_000;
29
30/// A moment, as files are ranked by it: a day, and a second of it, in UTC as recorded, or as
31/// the camera's clock said for when a photo was taken.
32pub(super) type Moment = (Day, u32);
33
34/// The moment of a time in milliseconds since 1970.
35pub(super) fn moment(millis: u64) -> Option<Moment> {
36	Day::from_unix_millis(millis, 0).map(|day| (day, Day::second_of_day(millis, 0)))
37}
38
39/// What a replica keeps of a space's sealed blobs, by the contents they seal.
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub(crate) enum Keeps {
42	/// Every blob: on an everyday device while no device of the space is an archive node.
43	All,
44	/// Every blob but those of these contents: on an archive node, the contents that only
45	/// files kept in place hold.
46	AllBut(BTreeSet<Hash>),
47	/// On an everyday device: the blobs of contents that no file of the space holds or held,
48	/// which every replica keeps, and those of the files' contents that it keeps.
49	Some {
50		/// Every content that a file of the space holds or held.
51		files: BTreeSet<Hash>,
52		/// The files' contents that it keeps.
53		kept: BTreeSet<Hash>,
54	},
55	/// No blob: on a device that drops the space, whose copies go as the copies elsewhere
56	/// are proven
57	/// ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
58	Nothing,
59}
60
61impl Keeps {
62	/// Whether a blob of this content is kept.
63	pub(crate) fn keeps(&self, content: &Hash) -> bool {
64		match self {
65			Self::All => true,
66			Self::AllBut(not) => !not.contains(content),
67			Self::Some { files, kept } => !files.contains(content) || kept.contains(content),
68			Self::Nothing => false,
69		}
70	}
71}
72
73/// What a space's files tell the plan.
74#[derive(Default)]
75struct Files {
76	/// Every content that a file of the space holds or held.
77	all: BTreeSet<Hash>,
78	/// The current content of each file that is neither deleted nor moved away, with its
79	/// size and the newest moment of the files that hold it.
80	current: BTreeMap<Hash, (Moment, u64)>,
81	/// The current contents kept whatever the size: those of files pinned to this device,
82	/// of trees with a root on it, and opened on it lately.
83	always: BTreeSet<Hash>,
84	/// The current contents that only files kept in place hold, whose originals stand for
85	/// them: no device keeps them sealed, but an everyday device those it keeps whatever the
86	/// size.
87	in_place: BTreeSet<Hash>,
88}
89
90/// A file's current content, as an everyday device ranks it against the others of every
91/// space.
92struct Ranked {
93	newest: Moment,
94	space: SpaceId,
95	content: Hash,
96	size: u64,
97}
98
99impl Library {
100	/// How many bytes of files this device keeps as an everyday device: as the person set it,
101	/// else a tenth of the size of the disk its replica is on, on a computer, and none on a
102	/// phone, which keeps thumbnails alone ([technical design: the planner]).
103	///
104	/// [technical design: the planner]: ../../../../docs/Technical-design.md#99-the-planner
105	///
106	/// # Errors
107	///
108	/// Returns an error if the personal space cannot be read.
109	pub fn keeps_up_to(&self) -> Result<u64, NodeError> {
110		Ok(self
111			.device_marks(self.info.device)?
112			.keeps
113			.unwrap_or_else(|| self.default_size()))
114	}
115
116	/// What this device keeps without a size set.
117	fn default_size(&self) -> u64 {
118		if place::whereabouts(&self.directory).phone {
119			return 0;
120		}
121		fs4::total_space(&self.directory).map_or(0, |total| total / SHARE_OF_DISK)
122	}
123
124	/// The files pinned to one of the person's devices, in any space, by their IDs.
125	///
126	/// # Errors
127	///
128	/// Returns an error if the personal space cannot be read.
129	pub fn pinned_files(&self, device: EntityId) -> Result<BTreeSet<EntityId>, NodeError> {
130		let state = self.space(self.info.personal)?.stored.log().state();
131		let device = state.canonical(device)?;
132		Ok(state
133			.current(device, &PINNED)?
134			.iter()
135			.filter_map(|statement| statement.value.as_reference())
136			.collect())
137	}
138
139	/// Pins a file of a space to one of the person's devices that holds the space, which then
140	/// keeps it whatever its size, or unpins it: in the personal space, where other members
141	/// never see it. The device keeps it from its next sync.
142	///
143	/// # Errors
144	///
145	/// Returns [`NodeError::NotAFile`] if `file` is no file of the space,
146	/// [`NodeError::WhichDevice`] if `device` is no device of the person's,
147	/// [`NodeError::DeviceLacksSpace`] if it does not hold the space, as its choices say, and
148	/// another error if the change cannot be saved.
149	pub fn pin_file(
150		&mut self,
151		(space, file): (SpaceId, EntityId),
152		device: EntityId,
153		pinned: bool,
154		wall_millis: u64,
155		rng: &mut impl CryptoRng,
156	) -> Result<(), NodeError> {
157		// The file, and those merged into it, any of which a pin made before may name.
158		let (file, members) = {
159			let state = self.space(space)?.stored.log().state();
160			let file = state.canonical(file)?;
161			if pinned && (state.is_deleted(file)? || !state.types(file)?.contains(&FILE)) {
162				return Err(NodeError::NotAFile(file.to_string()));
163			}
164			(file, state.merged(file)?)
165		};
166		let personal = self.info.personal;
167		let state = self.space(personal)?.stored.log().state();
168		let device = state.canonical(device)?;
169		if state.is_deleted(device)? || !state.types(device)?.contains(&DEVICE) {
170			return Err(NodeError::WhichDevice(format!(
171				"{device} is no device of yours"
172			)));
173		}
174		if pinned && !self.holding_devices(space)?.contains(&device) {
175			return Err(NodeError::DeviceLacksSpace);
176		}
177		let current: Vec<StatementId> = state
178			.current(device, &PINNED)?
179			.iter()
180			.filter(|statement| {
181				statement
182					.value
183					.as_reference()
184					.is_some_and(|pinned| pinned == file || members.contains(&pinned))
185			})
186			.map(|statement| statement.id)
187			.collect();
188		let operation = match (pinned, current.is_empty()) {
189			(true, true) => Operation::assert(Statement::new(
190				StatementId::random(rng),
191				device,
192				PINNED,
193				Value::Reference(file),
194			)),
195			(false, false) => Operation::retract(device, current),
196			_ => return Ok(()),
197		};
198		self.commit(personal, vec![operation], wall_millis, rng)
199	}
200
201	/// Records that a file of a space was opened on this device at `wall_millis`, outside the
202	/// history: an everyday device then keeps it whatever its size for a while, which makes
203	/// a sync fetch it, and ranks it by when it was last opened. It is never synced.
204	///
205	/// # Errors
206	///
207	/// Returns an error if the library has no such space, or the record cannot be saved.
208	pub fn record_opened(
209		&mut self,
210		space: SpaceId,
211		file: EntityId,
212		wall_millis: u64,
213	) -> Result<(), NodeError> {
214		let open = self
215			.spaces
216			.get_mut(&space)
217			.ok_or(NodeError::NoSpace(space))?;
218		let file = open.stored.log().state().canonical(file)?;
219		open.stored.record_opened(file, wall_millis)?;
220		Ok(())
221	}
222
223	/// The other replicas whose latest accounts list a sealed copy of a file's current
224	/// content, which a sync with one of them would bring: those to look for when the file is
225	/// opened on this device and it lacks the content.
226	///
227	/// # Errors
228	///
229	/// Returns an error if the library has no such space, or it cannot be read.
230	pub fn holders_of(
231		&self,
232		space: SpaceId,
233		file: EntityId,
234	) -> Result<Vec<crate::Replica>, NodeError> {
235		let content = {
236			let state = self.space(space)?.stored.log().state();
237			let file = state.canonical(file)?;
238			state
239				.current(file, &CONTENT)?
240				.iter()
241				.find_map(|statement| match statement.value {
242					Value::Blob(content) => Some(content),
243					_ => None,
244				})
245		};
246		let sealed: BTreeSet<Hash> = self.ordinary_sealed(space, content)?.into_iter().collect();
247		let mut holders = Vec::new();
248		for replica in self.replicas()?.into_iter().chain(self.peers()?) {
249			let Some(key) = replica.signing.filter(|_| !replica.this) else {
250				continue;
251			};
252			if holders
253				.iter()
254				.any(|holder: &crate::Replica| holder.signing == Some(key))
255			{
256				continue;
257			}
258			if self
259				.listed_blobs(space, &key)?
260				.is_some_and(|listed| !listed.is_disjoint(&sealed))
261			{
262				holders.push(replica);
263			}
264		}
265		Ok(holders)
266	}
267
268	/// What this replica keeps of each of its spaces' sealed blobs, as of `wall_millis`
269	/// ([technical design: the planner]).
270	///
271	/// [technical design: the planner]: ../../../../docs/Technical-design.md#99-the-planner
272	pub(crate) fn plan(&self, wall_millis: u64) -> Result<BTreeMap<SpaceId, Keeps>, NodeError> {
273		let marks = self.device_marks(self.info.device)?;
274		let archive = marks.role == DeviceRole::Archive;
275		let pinned = self.pinned_files(self.info.device)?;
276		let mut plan = BTreeMap::new();
277		let mut ranked = Vec::new();
278		let mut used: u64 = 0;
279		for &space in self.spaces.keys() {
280			if self.is_dropping(space) {
281				plan.insert(space, Keeps::Nothing);
282				continue;
283			}
284			if !archive && !self.has_archive_node(space)? {
285				plan.insert(space, Keeps::All);
286				continue;
287			}
288			let files = self.planned_files(space, (&pinned, archive), wall_millis)?;
289			if archive {
290				plan.insert(space, Keeps::AllBut(files.in_place));
291				continue;
292			}
293			for content in &files.always {
294				used = used.saturating_add(files.current.get(content).map_or(0, |(_, size)| *size));
295			}
296			ranked.extend(
297				files
298					.current
299					.iter()
300					.filter(|(content, _)| !files.always.contains(*content))
301					.map(|(content, (newest, size))| Ranked {
302						newest: *newest,
303						space,
304						content: *content,
305						size: *size,
306					}),
307			);
308			plan.insert(
309				space,
310				Keeps::Some {
311					files: files.all,
312					kept: files.always,
313				},
314			);
315		}
316		if !ranked.is_empty() {
317			let size = marks.keeps.unwrap_or_else(|| self.default_size());
318			// Newest first, each that still fits: one too large for what is left is passed
319			// over, so that one large file leaves room for the smaller ones after it.
320			ranked.sort_by(|a, b| {
321				b.newest
322					.cmp(&a.newest)
323					.then(a.space.cmp(&b.space))
324					.then(a.content.cmp(&b.content))
325			});
326			for each in ranked {
327				let Some(after) = used.checked_add(each.size).filter(|after| *after <= size) else {
328					continue;
329				};
330				used = after;
331				if let Some(Keeps::Some { kept, .. }) = plan.get_mut(&each.space) {
332					kept.insert(each.content);
333				}
334			}
335		}
336		Ok(plan)
337	}
338
339	/// What a space's files tell the plan: which contents only files kept in place hold; and
340	/// on an everyday device, each other current content with when its newest file was taken
341	/// or recorded, or last opened here, and which are kept whatever the size.
342	fn planned_files(
343		&self,
344		space: SpaceId,
345		(pinned, archive): (&BTreeSet<EntityId>, bool),
346		wall_millis: u64,
347	) -> Result<Files, NodeError> {
348		let open = self.space(space)?;
349		let state = open.stored.log().state();
350		let storage = state.storage();
351		let opened = open.stored.opened()?;
352		let trees_here = self.trees_here(space)?;
353		let policies = self.read_policies(space)?;
354		let mut files = Files::default();
355		let (mut in_store, mut in_place) = (BTreeSet::new(), BTreeSet::new());
356		let mut seen = BTreeSet::new();
357		for file in open
358			.stored
359			.find(&fields::TYPE, &Value::Text(FILE.to_string()))?
360		{
361			let file = state.canonical(file)?;
362			if !seen.insert(file) {
363				continue;
364			}
365			let members = state.merged(file)?;
366			// Every content that it, or a file merged into it, holds or held.
367			for &member in &members {
368				for id in storage.of_field(member, &CONTENT)? {
369					if let Some(recorded) = storage.get(id)?
370						&& let Value::Blob(content) = recorded.statement.value
371					{
372						files.all.insert(content);
373					}
374				}
375			}
376			if gone(state, file)? || !state.types(file)?.contains(&FILE) {
377				continue;
378			}
379			let Some((content, statement)) =
380				state
381					.current(file, &CONTENT)?
382					.into_iter()
383					.find_map(|statement| match statement.value {
384						Value::Blob(content) => Some((content, statement.id)),
385						_ => None,
386					})
387			else {
388				continue;
389			};
390			let choice = policies.choose(&own_choices(state, file)?, &facts_of(state, file)?);
391			if choice.needs.kept == Kept::Store {
392				in_store.insert(content);
393			} else {
394				in_place.insert(content);
395			}
396			if archive {
397				continue;
398			}
399			let opened_at = members
400				.iter()
401				.filter_map(|member| opened.get(member))
402				.max()
403				.copied();
404			let taken = taken_of(state, file)?;
405			let recorded = storage
406				.get(statement)?
407				.and_then(|recorded| moment(recorded.at.millis()));
408			let newest = [taken.or(recorded), opened_at.and_then(moment)]
409				.into_iter()
410				.flatten()
411				.max()
412				.unwrap_or((
413					Day::from_days_since_epoch(0).unwrap_or_else(|| unreachable!()),
414					0,
415				));
416			let size = size_of(state, file)?.unwrap_or(0);
417			let mut in_tree_here = false;
418			for tree in state
419				.current(file, &IN_TREE)?
420				.iter()
421				.filter_map(|statement| statement.value.as_reference())
422			{
423				in_tree_here |= trees_here.contains(&state.canonical(tree)?);
424			}
425			let lately = opened_at.is_some_and(|at| wall_millis.saturating_sub(at) < OPENED_FOR);
426			if in_tree_here || lately || members.iter().any(|member| pinned.contains(member)) {
427				files.always.insert(content);
428			}
429			let entry = files.current.entry(content).or_insert((newest, size));
430			entry.0 = entry.0.max(newest);
431		}
432		files.in_place = in_place.difference(&in_store).copied().collect();
433		// Nor does an everyday device keep the contents that only files kept in place hold,
434		// whose originals stand for them, but those it keeps whatever the size.
435		let (in_place, always) = (&files.in_place, &files.always);
436		files
437			.current
438			.retain(|content, _| !in_place.contains(content) || always.contains(content));
439		Ok(files)
440	}
441
442	/// The trees of a space with a root on this device, not deleted.
443	fn trees_here(&self, space: SpaceId) -> Result<BTreeSet<EntityId>, NodeError> {
444		let open = self.space(space)?;
445		let state = open.stored.log().state();
446		let mut trees = BTreeSet::new();
447		for root in open
448			.stored
449			.find(&fields::TYPE, &Value::Text(TREE_ROOT.to_string()))?
450		{
451			let root = state.canonical(root)?;
452			if state.is_deleted(root)?
453				|| !state
454					.current(root, &ON_DEVICE)?
455					.iter()
456					.any(|statement| statement.value.as_reference() == Some(self.info.device))
457			{
458				continue;
459			}
460			for statement in state.current(root, &ROOT_OF)? {
461				if let Some(tree) = statement.value.as_reference() {
462					trees.insert(state.canonical(tree)?);
463				}
464			}
465		}
466		Ok(trees)
467	}
468}
469
470/// When a photo or a video was taken, as its `std.taken` starts.
471pub(super) fn taken_of<S: Statements>(
472	state: &State<S>,
473	file: EntityId,
474) -> Result<Option<Moment>, NodeError>
475where
476	NodeError: From<S::Error>,
477{
478	Ok(state
479		.current(file, &TAKEN)?
480		.first()
481		.and_then(|statement| match &statement.value {
482			Value::Date(taken) => match taken.start() {
483				Start::At { day, second } => Some((day, second.unwrap_or(0))),
484				Start::BeginningOfTime => None,
485			},
486			_ => None,
487		}))
488}
489
490/// Whether an entity is gone from its space: deleted, or moved to another.
491pub(super) fn gone<S: Statements>(state: &State<S>, entity: EntityId) -> Result<bool, NodeError>
492where
493	NodeError: From<S::Error>,
494{
495	Ok(state.is_deleted(entity)? || !state.current(entity, &fields::MOVED_INTO)?.is_empty())
496}