Skip to main content

nibkeep_node/library/
waiting.rs

1//! Copies that wait before purging: an archive node keeps apart what a purge destroys for a
2//! while, 30 days by default, during which its owner can stop the purge, which gives back what
3//! it destroyed, or end the wait early ([technical design: copies that wait]).
4//!
5//! [technical design: copies that wait]: ../../../../docs/Technical-design.md#911-copies-that-wait
6
7use std::collections::{BTreeMap, BTreeSet};
8use std::path::PathBuf;
9
10use nibkeep_base::{ChangeId, EntityId, SpaceId};
11use nibkeep_crypto::rand_core::CryptoRng;
12use nibkeep_log::{DeviceRole, Kept};
13
14use super::Library;
15use super::accounts::DeviceMarks;
16use crate::NodeError;
17
18/// A day, in milliseconds.
19pub const DAY: u64 = 86_400_000;
20
21/// How many days an archive node, or a backup, waits unless its owner says otherwise: 30.
22pub const DEFAULT_WAIT_DAYS: u64 = 30;
23
24/// The longest wait an owner may set, in days: 365.
25pub const MOST_WAIT_DAYS: u64 = 365;
26
27/// How many days a device waits before purging, as marked: an archive node its own number of
28/// days, or 30 without one; an everyday device none.
29#[must_use]
30pub fn wait_days(marks: &DeviceMarks) -> u64 {
31	match marks.role {
32		DeviceRole::Archive => marks.waits.unwrap_or(DEFAULT_WAIT_DAYS).min(MOST_WAIT_DAYS),
33		DeviceRole::Everyday => 0,
34	}
35}
36
37/// How many days a backup waits before purging, as marked: its own number of days, or 30
38/// without one.
39#[must_use]
40pub fn backup_wait_days(backup: &super::backups::Backup) -> u64 {
41	backup
42		.waits
43		.unwrap_or(DEFAULT_WAIT_DAYS)
44		.min(MOST_WAIT_DAYS)
45}
46
47/// The wait in force at a time, by a device's history of waits, in milliseconds: that of the
48/// latest entry from that time or before, or none before the first.
49pub(crate) fn wait_at(waits: &[(u64, u64)], at: u64) -> u64 {
50	waits
51		.iter()
52		.rev()
53		.find(|(since, _)| *since <= at)
54		.map_or(0, |(_, wait)| *wait)
55}
56
57/// A device's history of waits brought up to date at `now` with the wait its marks ask for:
58/// a longer wait holds at once, and a shorter one, or none, only once the wait before it has
59/// passed, so that a device that turned against its user cannot shorten the wait and purge at
60/// once. Returns `None` if nothing changes.
61pub(crate) fn waits_marked(waits: &[(u64, u64)], marked: u64, now: u64) -> Option<Vec<(u64, u64)>> {
62	match waits.last() {
63		Some((_, last)) if *last == marked => return None,
64		None if marked == 0 => return None,
65		_ => {}
66	}
67	// What was to come no longer does: the marks say otherwise now.
68	let mut waits: Vec<(u64, u64)> = waits
69		.iter()
70		.copied()
71		.filter(|(since, _)| *since <= now)
72		.collect();
73	let before = wait_at(&waits, now);
74	if marked >= before {
75		waits.push((now, marked));
76	} else {
77		waits.push((now.saturating_add(before), marked));
78	}
79	Some(waits)
80}
81
82/// A purge whose destruction this replica keeps apart while it waits.
83#[derive(Clone, Debug, PartialEq, Eq)]
84pub struct WaitingPurge {
85	/// The space.
86	pub space: SpaceId,
87	/// The purge.
88	pub purge: ChangeId,
89	/// When this replica took it in, in milliseconds since 1970.
90	pub received: u64,
91	/// When the wait ends, after which what it destroyed goes for good.
92	pub ends: u64,
93	/// How many changes it purged whose payloads and keys are kept.
94	pub changes: usize,
95	/// How many secret values it purged whose keys are kept.
96	pub secrets: usize,
97	/// How many sealed blobs it purged whose keys are kept.
98	pub blobs: usize,
99	/// How many bytes of sealed blobs are kept apart for it.
100	pub bytes: u64,
101	/// The backup it waits on, if it waits on a backup plugged in here rather than on this
102	/// device.
103	pub on: Option<WaitingOn>,
104}
105
106/// A backup that a purge waits on.
107#[derive(Clone, Debug, PartialEq, Eq)]
108pub struct WaitingOn {
109	/// The backup's record.
110	pub backup: EntityId,
111	/// Its name.
112	pub name: String,
113	/// Its folder, here.
114	pub folder: PathBuf,
115	/// How many items and files of what the purge destroyed it keeps.
116	pub items: u64,
117}
118
119/// A copy that waits before destroying what a purge destroys, as a purge names them before
120/// the person confirms: the person's archive nodes and backups, and other members'.
121#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct WaitingCopy {
123	/// Its name: the device's, or the backup's, if this replica knows it.
124	pub name: Option<String>,
125	/// Whether it is this device.
126	pub this: bool,
127	/// Whether it is a backup, whose wait counts from its next update.
128	pub backup: bool,
129	/// For another member's copy, that member's name, if known.
130	pub member: Option<String>,
131	/// Whether it is another member's.
132	pub others: bool,
133	/// How many days it waits.
134	pub days: u64,
135}
136
137impl Library {
138	/// How many days this device waits before purging, as marked now.
139	///
140	/// # Errors
141	///
142	/// Returns an error if the personal space cannot be read.
143	pub fn own_wait_days(&self) -> Result<u64, NodeError> {
144		Ok(wait_days(&self.device_marks(self.info.device)?))
145	}
146
147	/// The wait in force on this device at a time, in milliseconds, as its history of waits
148	/// says.
149	///
150	/// # Errors
151	///
152	/// Returns an error if the personal space cannot be read.
153	pub(crate) fn wait_in_force(&self, at: u64) -> Result<u64, NodeError> {
154		let waits = self.space(self.info.personal)?.stored.waits()?;
155		Ok(wait_at(&waits, at))
156	}
157
158	/// Brings this device's history of waits up to date with its marks at `now`, keeps what
159	/// purges destroy in every space while a wait is in force, and returns the wait in force
160	/// now, in milliseconds.
161	///
162	/// # Errors
163	///
164	/// Returns an error if the personal space cannot be read or written.
165	pub(crate) fn refresh_wait(&mut self, now: u64) -> Result<u64, NodeError> {
166		let marked = self.own_wait_days()?.saturating_mul(DAY);
167		let personal = self.info.personal;
168		let open = self
169			.spaces
170			.get_mut(&personal)
171			.ok_or(NodeError::NoSpace(personal))?;
172		let waits = open.stored.waits()?;
173		let waits = match waits_marked(&waits, marked, now) {
174			Some(changed) => {
175				open.stored.save_waits(changed.clone(), &open.keys)?;
176				changed
177			}
178			None => waits,
179		};
180		let wait = wait_at(&waits, now);
181		// A wait to come, after a shorter one, keeps too, as what it keeps may stay that long.
182		let keeping = wait > 0;
183		for open in self.spaces.values_mut() {
184			open.stored.keep_destroyed(keeping);
185		}
186		Ok(wait)
187	}
188
189	/// Keeps what purges destroy in a space just opened, as the other spaces do, which the
190	/// wait in force set ([`Library::refresh_wait`]).
191	pub(crate) fn keep_in(&mut self, space: SpaceId) {
192		let keeping = self
193			.spaces
194			.get(&self.info.personal)
195			.is_some_and(|open| open.stored.keeps_destroyed());
196		if let Some(open) = self.spaces.get_mut(&space) {
197			open.stored.keep_destroyed(keeping);
198		}
199	}
200
201	/// The purges whose destruction this replica keeps apart, by space and then by when it
202	/// took them in, with when each wait ends.
203	///
204	/// # Errors
205	///
206	/// Returns an error if a space cannot be read.
207	pub fn waiting_purges(&self) -> Result<Vec<WaitingPurge>, NodeError> {
208		let waits = self.space(self.info.personal)?.stored.waits()?;
209		let mut waiting = Vec::new();
210		for (&space, open) in &self.spaces {
211			let mut by_purge: BTreeMap<ChangeId, WaitingPurge> = BTreeMap::new();
212			for row in open.stored.kept()? {
213				let entry = by_purge.entry(row.purge).or_insert_with(|| WaitingPurge {
214					space,
215					purge: row.purge,
216					received: row.received,
217					ends: row.received.saturating_add(wait_at(&waits, row.received)),
218					changes: 0,
219					secrets: 0,
220					blobs: 0,
221					bytes: 0,
222					on: None,
223				});
224				match &row.part {
225					Kept::Change(_) => entry.changes += 1,
226					Kept::RecordKeys(..) => entry.secrets += 1,
227					Kept::BlobKeys(sealed, _) => {
228						entry.blobs += 1;
229						entry.bytes += open.stored.kept_blob_size(sealed).unwrap_or(0);
230					}
231				}
232			}
233			let mut purges: Vec<WaitingPurge> = by_purge.into_values().collect();
234			purges.sort_by_key(|purge| (purge.received, purge.purge));
235			waiting.extend(purges);
236		}
237		Ok(waiting)
238	}
239
240	/// The purges that wait on the backups `found` here before what they destroyed leaves
241	/// them, as each backup's record says, by backup and then by when each came.
242	///
243	/// # Errors
244	///
245	/// Returns an error if a space cannot be read.
246	pub fn waiting_purges_on(
247		&self,
248		found: &[(super::backups::Backup, PathBuf)],
249	) -> Result<Vec<WaitingPurge>, NodeError> {
250		let mut waiting = Vec::new();
251		for (backup, folder) in found {
252			let record = crate::backup::read_record(&crate::backup::InFileSystem::new(folder));
253			let mut purges = Vec::new();
254			for (&purge, &(seen, items)) in &record.purges {
255				let mut space = None;
256				for (&id, open) in &self.spaces {
257					if open.stored.log().contains(purge)? {
258						space = Some(id);
259						break;
260					}
261				}
262				let Some(space) = space else {
263					continue;
264				};
265				purges.push(WaitingPurge {
266					space,
267					purge,
268					received: seen,
269					ends: seen.saturating_add(wait_at(&record.waits, seen)),
270					changes: 0,
271					secrets: 0,
272					blobs: 0,
273					bytes: 0,
274					on: Some(WaitingOn {
275						backup: backup.id,
276						name: backup.name.clone(),
277						folder: folder.clone(),
278						items,
279					}),
280				});
281			}
282			purges.sort_by_key(|purge| (purge.received, purge.purge));
283			waiting.extend(purges);
284		}
285		Ok(waiting)
286	}
287
288	/// The places where the purge that `name` names waits, on this device and on the backups
289	/// `found` here: `name` is the start of its ID, as `nib purges` shows it; `on`, if given,
290	/// names one backup, by its name or ID, or `here` this device.
291	///
292	/// # Errors
293	///
294	/// Returns [`NodeError::WhichPurge`] if it names no purge that waits there, or several.
295	pub fn find_waiting_purges(
296		&self,
297		name: &str,
298		(found, on): (&[(super::backups::Backup, PathBuf)], Option<&str>),
299	) -> Result<Vec<WaitingPurge>, NodeError> {
300		let name = name.trim();
301		let mut all = self.waiting_purges()?;
302		all.extend(self.waiting_purges_on(found)?);
303		let named: Vec<WaitingPurge> = all
304			.into_iter()
305			.filter(|waiting| !name.is_empty() && waiting.purge.to_string().starts_with(name))
306			.filter(|waiting| match (on, &waiting.on) {
307				(None, _) => true,
308				(Some(on), None) => on.eq_ignore_ascii_case("here"),
309				(Some(on), Some(backup)) => {
310					backup.name.eq_ignore_ascii_case(on) || backup.backup.to_string() == on
311				}
312			})
313			.collect();
314		let purges: BTreeSet<ChangeId> = named.iter().map(|waiting| waiting.purge).collect();
315		match purges.len() {
316			1 => Ok(named),
317			0 => Err(NodeError::WhichPurge(format!(
318				"no purge that waits on this device, or on a backup plugged in here, starts with {name}"
319			))),
320			_ => Err(NodeError::WhichPurge(format!(
321				"several purges that wait here start with {name}; give more of the ID"
322			))),
323		}
324	}
325
326	/// Stops a purge where it waits, as `waiting` lists the places of one purge: makes one
327	/// change that restores what it destroyed and they keep, which every replica takes, and
328	/// gives back what this replica kept, and from each backup, through an update of it, what
329	/// the backup kept, so that what was purged counts again as it was. Returns the backups
330	/// updated: one that another program holds is not, and gives back at its next update.
331	///
332	/// # Errors
333	///
334	/// Returns [`NodeError::CannotRestore`] if this member's role does not allow it: an admin
335	/// may stop any purge, an editor one of the changes their member's replicas signed, and
336	/// nothing is made; and another error if a space or a backup cannot be read or written.
337	pub fn stop_purge(
338		&mut self,
339		waiting: &[WaitingPurge],
340		wall_millis: u64,
341		rng: &mut impl CryptoRng,
342	) -> Result<Vec<super::backups::Backup>, NodeError> {
343		let Some(first) = waiting.first() else {
344			return Ok(Vec::new());
345		};
346		let (space, purge) = (first.space, first.purge);
347		self.check_not_revoked(space)?;
348		self.check_not_ai_agent("stop a purge")?;
349		// What each backup keeps of it comes back from the backup, through an update.
350		let mut also = nibkeep_log::Restores::default();
351		let mut from = Vec::new();
352		for on in waiting.iter().filter_map(|waiting| waiting.on.as_ref()) {
353			let backup = self.own_backup(on)?;
354			let kept = self
355				.backup_kept_of(&backup, &on.folder, (space, purge))?
356				.ok_or_else(|| {
357					NodeError::WhichPurge(format!(
358						"another program updates the backup {} now; try again",
359						on.name
360					))
361				})?;
362			also.changes.extend(kept.changes);
363			also.statements.extend(kept.statements);
364			also.blobs.extend(kept.blobs);
365			from.push((backup, on.folder.clone()));
366		}
367		let signing = &self.replica.signing;
368		let code_types = &self.code_types;
369		let open = self
370			.spaces
371			.get_mut(&space)
372			.ok_or(NodeError::NoSpace(space))?;
373		let restore =
374			match open
375				.stored
376				.restore_kept(signing, &open.keys, (purge, &also), wall_millis, rng)
377			{
378				Err(nibkeep_store::StoreError::Log(nibkeep_log::LogError::CannotRestore)) => {
379					return Err(NodeError::CannotRestore);
380				}
381				restore => restore?,
382			};
383		open.read_types(code_types)?;
384		if restore.is_none() {
385			return Err(NodeError::WhichPurge(format!(
386				"nothing of the purge {purge} waits here"
387			)));
388		}
389		if space == self.info.personal {
390			self.refresh_languages()?;
391		}
392		let mut updated = Vec::new();
393		for (backup, folder) in from {
394			let now = || wall_millis;
395			if self
396				.update_backup(&backup, &folder, &now, &|| false)?
397				.is_some()
398			{
399				updated.push(backup);
400			}
401		}
402		Ok(updated)
403	}
404
405	/// The person's backup that a purge waits on.
406	fn own_backup(&self, on: &WaitingOn) -> Result<super::backups::Backup, NodeError> {
407		self.backups()?
408			.into_iter()
409			.find(|backup| backup.id == on.backup)
410			.ok_or_else(|| NodeError::WhichBackup(format!("{} is no backup of yours", on.name)))
411	}
412
413	/// Ends the wait of a purge where it waits, as `waiting` lists the places of one purge:
414	/// destroys what this replica kept of what it destroyed, and has each backup let it go
415	/// at once, through an update of it. Returns how many parts went, and the backups updated.
416	///
417	/// # Errors
418	///
419	/// Returns [`NodeError::WhichPurge`] if another program updates a backup now, and another
420	/// error if a space or a backup cannot be written.
421	pub fn end_wait(
422		&mut self,
423		waiting: &[WaitingPurge],
424		wall_millis: u64,
425	) -> Result<(usize, Vec<super::backups::Backup>), NodeError> {
426		let mut gone = 0;
427		let mut updated = Vec::new();
428		for place in waiting {
429			if let Some(on) = &place.on {
430				let backup = self.own_backup(on)?;
431				let now = || wall_millis;
432				let ending = BTreeSet::from([place.purge]);
433				let done = self
434					.update_backup_ending(&backup, &on.folder, (&now, &|| false), &ending)?
435					.ok_or_else(|| {
436						NodeError::WhichPurge(format!(
437							"another program updates the backup {} now; try again",
438							on.name
439						))
440					})?;
441				gone += done.purged;
442				updated.push(backup);
443			} else {
444				let open = self
445					.spaces
446					.get_mut(&place.space)
447					.ok_or(NodeError::NoSpace(place.space))?;
448				gone += open
449					.stored
450					.destroy_kept(&BTreeSet::from([place.purge]), &open.keys)?;
451			}
452		}
453		Ok((gone, updated))
454	}
455
456	/// Destroys what this replica keeps apart of the purges whose wait has ended at `now`, as
457	/// the holder of the sync role does in its passes, after bringing the wait up to date
458	/// with the marks. Returns how many parts went.
459	///
460	/// # Errors
461	///
462	/// Returns an error if a space cannot be read or written.
463	pub fn destroy_due(&mut self, now: u64) -> Result<usize, NodeError> {
464		self.refresh_wait(now)?;
465		let mut destroyed = 0;
466		let due: Vec<(SpaceId, ChangeId)> = self
467			.waiting_purges()?
468			.into_iter()
469			.filter(|waiting| waiting.ends <= now)
470			.map(|waiting| (waiting.space, waiting.purge))
471			.collect();
472		let mut by_space: BTreeMap<SpaceId, BTreeSet<ChangeId>> = BTreeMap::new();
473		for (space, purge) in due {
474			by_space.entry(space).or_default().insert(purge);
475		}
476		for (space, purges) in by_space {
477			let open = self
478				.spaces
479				.get_mut(&space)
480				.ok_or(NodeError::NoSpace(space))?;
481			destroyed += open.stored.destroy_kept(&purges, &open.keys)?;
482		}
483		Ok(destroyed)
484	}
485
486	/// After a sync: brings this device's wait up to date with marks that may have come, and
487	/// gives back what a restore that came brought back, as [`Library::take_back_restored`]
488	/// does.
489	///
490	/// # Errors
491	///
492	/// Returns an error if a space cannot be read or written.
493	pub fn settle_waiting(&mut self, now: u64) -> Result<usize, NodeError> {
494		self.refresh_wait(now)?;
495		self.take_back_restored(now, false)
496	}
497
498	/// Gives back what this replica keeps apart where a change that restores it came to
499	/// count, as after a sync brought one, or at `now` once the library opened. Returns how
500	/// many parts came back.
501	///
502	/// # Errors
503	///
504	/// Returns an error if a space cannot be read or written.
505	pub fn take_back_restored(&mut self, now: u64, opening: bool) -> Result<usize, NodeError> {
506		let mut given = 0;
507		let code_types = self.code_types.clone();
508		for open in self.spaces.values_mut() {
509			if opening || open.stored.restored_since() {
510				let back = open.stored.take_back_kept(&open.keys, now)?;
511				if back > 0 {
512					// What came back may define types.
513					open.read_types(&code_types)?;
514				}
515				given += back;
516			}
517		}
518		Ok(given)
519	}
520
521	/// The copies that wait before destroying what a purge of `space` destroys: the person's
522	/// archive nodes listed in that space, this device first, as their marks say; their
523	/// backups of it; and other members' archive nodes and backups, as their accounts say.
524	///
525	/// # Errors
526	///
527	/// Returns an error if a space cannot be read.
528	pub fn waiting_copies(&self, space: SpaceId) -> Result<Vec<WaitingCopy>, NodeError> {
529		let copy = |name: Option<String>, days: u64| WaitingCopy {
530			name,
531			this: false,
532			backup: false,
533			member: None,
534			others: false,
535			days,
536		};
537		let mut own: BTreeMap<EntityId, WaitingCopy> = BTreeMap::new();
538		let mut own_keys = BTreeSet::new();
539		for replica in self.replicas()? {
540			if let Some(key) = replica.signing {
541				own_keys.insert(*key.as_bytes());
542			}
543			if replica.revoked || replica.deleted {
544				continue;
545			}
546			let Some(device) = replica.device else {
547				continue;
548			};
549			let days = wait_days(&replica.marks);
550			if days == 0 || own.contains_key(&device) {
551				continue;
552			}
553			let holds = match replica.signing {
554				Some(key) => self.counts_in(space, &key)?,
555				None => false,
556			};
557			if holds {
558				let mut waiting = copy(replica.device_name.clone(), days);
559				waiting.this = device == self.info.device;
560				own.insert(device, waiting);
561			}
562		}
563		let mut copies: Vec<WaitingCopy> = own.into_values().collect();
564		copies.sort_by(|a, b| (!a.this, &a.name).cmp(&(!b.this, &b.name)));
565		// The person's backups of the space, as marked.
566		let mut known_backups = BTreeSet::new();
567		for backup in self.backups()? {
568			known_backups.insert(backup.id);
569			if !self.backup_spaces(&backup)?.contains(&space) {
570				continue;
571			}
572			let days = backup_wait_days(&backup);
573			if days > 0 {
574				let mut waiting = copy(Some(backup.name.clone()), days);
575				waiting.backup = true;
576				copies.push(waiting);
577			}
578		}
579		// Other members' archive nodes, once for each disk, as their accounts say.
580		let peers: BTreeMap<[u8; 32], crate::Replica> = self
581			.peers()?
582			.into_iter()
583			.filter_map(|peer| peer.signing.map(|key| (*key.as_bytes(), peer)))
584			.collect();
585		let mut disks = BTreeSet::new();
586		for (author, head) in self.other_heads(space)? {
587			if own_keys.contains(&author)
588				|| head.role != DeviceRole::Archive
589				|| head.waits == 0
590				|| !disks.insert(head.disk)
591			{
592				continue;
593			}
594			let peer = peers.get(&author);
595			let mut waiting = copy(peer.and_then(|peer| peer.device_name.clone()), head.waits);
596			waiting.member = peer.and_then(|peer| peer.member.clone());
597			waiting.others = true;
598			copies.push(waiting);
599		}
600		// And others' backups, as the latest update of each says.
601		for (backup, account) in self.backup_accounts(space)? {
602			if known_backups.contains(&backup)
603				|| self.backup_forgotten(backup)?
604				|| account.head.waits == 0
605			{
606				continue;
607			}
608			let mut waiting = copy(None, account.head.waits);
609			waiting.backup = true;
610			waiting.others = true;
611			copies.push(waiting);
612		}
613		Ok(copies)
614	}
615}
616
617#[cfg(test)]
618mod tests {
619	use super::*;
620
621	#[test]
622	fn a_longer_wait_holds_at_once_and_a_shorter_one_after_the_wait_before_it() {
623		let day = DAY;
624		// None marked, none kept.
625		assert_eq!(waits_marked(&[], 0, 10), None);
626		let waits = waits_marked(&[], 30 * day, 10).expect("a wait");
627		assert_eq!(waits, [(10, 30 * day)]);
628		assert_eq!(waits_marked(&waits, 30 * day, 20), None);
629		// Longer at once.
630		let longer = waits_marked(&waits, 60 * day, 20).expect("longer");
631		assert_eq!(wait_at(&longer, 20), 60 * day);
632		// Shorter, or none, after the wait before it.
633		let none = waits_marked(&longer, 0, 30).expect("none");
634		assert_eq!(wait_at(&none, 30), 60 * day);
635		assert_eq!(wait_at(&none, 30 + 60 * day - 1), 60 * day);
636		assert_eq!(wait_at(&none, 30 + 60 * day), 0);
637		// Still none marked: what is to come stays as it was.
638		assert_eq!(waits_marked(&none, 0, 40), None);
639		// Marked again before it came, shorter than the wait in force: the wait holds, and
640		// the new one comes after it.
641		let again = waits_marked(&none, 30 * day, 50).expect("again");
642		assert_eq!(wait_at(&again, 50), 60 * day);
643		assert_eq!(wait_at(&again, 50 + 60 * day), 30 * day);
644		assert_eq!(wait_at(&again, 50 + 365 * day), 30 * day);
645	}
646}