Skip to main content

nibkeep_node/library/
accounts.rs

1//! Where the copies are: each replica's account of what it holds in a space, which it brings
2//! up to date before each sync and which syncs pass on; the marks that people give their
3//! devices; and the disks that hold each file's copies and the space's changes
4//! ([technical design: where the copies are]).
5//!
6//! [technical design: where the copies are]: ../../../../docs/Technical-design.md#96-where-the-copies-are
7
8use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
9
10use nibkeep_base::{ChangeId, EntityId, Hash, SpaceId, StatementId};
11use nibkeep_crypto::VerifyingKey;
12use nibkeep_crypto::rand_core::CryptoRng;
13use nibkeep_governance::{AWAY, DEVICE, DEVICE_ROLE, KEEPS_UP_TO, WAITS};
14use nibkeep_log::{AccountPage, BackupHead, DeviceRole, Head, History as _, PageBody, PageKind};
15use nibkeep_model::{Operation, Statement, Value};
16use nibkeep_store::StoredPage;
17
18use super::Library;
19use super::checking::COUNTS_FOR_MILLIS;
20use crate::{NodeError, place};
21
22/// The context of the key, derived from a space's ID, that a disk's name is hashed with.
23const DISK_CONTEXT: &str = "nibkeep 2026-11 disk";
24
25/// How many of the newest changes a check looks at to count those held here alone.
26const NEWEST_LOOKED_AT: usize = 10_000;
27
28/// How long a replica's account of a space stands without being brought up to date while
29/// the space's state stays the same, in milliseconds: a minute, so that what changed beside
30/// the state, such as a blob that came on its own or an original changed where it was
31/// found, shows at a sync a minute later.
32const REFRESHED_FOR: u64 = 60_000;
33
34/// How many backups one replica's pages may tell of in a space: 8.
35const BACKUPS_PER_REPLICA: usize = 8;
36
37/// How a person marked a device, in the personal space.
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39pub struct DeviceMarks {
40	/// What it does with the files of its spaces: every device is an everyday device unless
41	/// marked as an archive node.
42	pub role: DeviceRole,
43	/// Whether it is kept away from home.
44	pub away: bool,
45	/// How many bytes of files it keeps as an everyday device, if the person set it; without
46	/// it, a tenth of its disk on a computer, and none on a phone
47	/// ([`Library::keeps_up_to`]).
48	pub keeps: Option<u64>,
49	/// How many days it waits before it destroys what a purge destroys, as an archive node,
50	/// if the person set it, 0 for none; without it, 30 ([`super::waiting::wait_days`]).
51	pub waits: Option<u64>,
52}
53
54/// A disk that holds copies of a space's files or changes, as this replica holds them now
55/// and the other replicas' accounts say.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct Disk {
58	/// Its ID in the space.
59	pub id: Hash,
60	/// Whether this replica is on it.
61	pub here: bool,
62	/// The replicas on it whose accounts came, this one first if it is on it.
63	pub replicas: Vec<DiskReplica>,
64	/// Whether it is an archive node's: every replica on it says that its device is one.
65	pub archive: bool,
66	/// Whether it is kept away from home: every replica on it says that its device is.
67	pub away: bool,
68	/// When the latest head of an account of a replica on it was issued, in milliseconds
69	/// since 1970, if one is kept: this replica's own, on its disk.
70	pub issued: Option<u64>,
71	/// How many copies the checks of the replicas on it found damaged in the last 4 weeks,
72	/// as their accounts say: this replica's as it knows now.
73	pub damaged: u64,
74	/// How many of the copies that their checks found damaged are damaged still.
75	pub unrepaired: u64,
76	/// The backups on it whose accounts came.
77	pub backups: Vec<DiskBackup>,
78}
79
80/// A backup on a disk ([technical design: backups]).
81///
82/// [technical design: backups]: ../../../../docs/Technical-design.md#910-backups
83#[derive(Clone, Debug, PartialEq, Eq)]
84pub struct DiskBackup {
85	/// Its record's ID.
86	pub backup: EntityId,
87	/// Its name, if it is one of this user's, whose personal space names it.
88	pub name: Option<String>,
89	/// The number of its update that its account tells of.
90	pub update: u64,
91}
92
93/// A replica on a disk.
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct DiskReplica {
96	/// Its record, if this replica knows it.
97	pub replica: Option<EntityId>,
98	/// Its name: the name of the app that keeps it.
99	pub name: Option<String>,
100	/// Its device's name.
101	pub device: Option<String>,
102	/// For another user's replica, the name of the member it is of.
103	pub member: Option<String>,
104	/// Whether it is this replica.
105	pub this: bool,
106}
107
108/// How a disk holds a copy of a file.
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub enum CopyHeld {
111	/// Sealed in a store, last read in full and found intact at this time, in milliseconds
112	/// since 1970, if ever.
113	Sealed {
114		/// When it was last checked.
115		checked: Option<u64>,
116	},
117	/// As a plain copy, unchanged: an original kept where it was found, or a checkout, last
118	/// read in full and found holding the content at this time, in milliseconds since 1970,
119	/// if ever.
120	InPlace {
121		/// When it was last checked.
122		checked: Option<u64>,
123	},
124}
125
126/// A disk that holds a copy of a file, and how.
127#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct FileCopy {
129	/// The disk.
130	pub disk: Disk,
131	/// How it holds the copy.
132	pub held: CopyHeld,
133	/// Whether the copy counts: it was checked in the last 8 weeks
134	/// ([technical design: checking and repair]).
135	///
136	/// [technical design: checking and repair]: ../../../../docs/Technical-design.md#97-checking-and-repair
137	pub counts: bool,
138}
139
140/// How the space's changes are held, as a check counts them against the space's Critical
141/// policy.
142#[derive(Clone, Debug, PartialEq, Eq)]
143pub struct ChangeCopies {
144	/// What the Critical policy asks.
145	pub needs: crate::Needs,
146	/// How many disks hold every change that this replica holds, its own included.
147	pub disks: usize,
148	/// How many of them are away from home.
149	pub away: usize,
150	/// How many of them are archive nodes'.
151	pub archived: usize,
152	/// How many of the changes this replica holds are held on its disk alone.
153	pub here_alone: usize,
154	/// Whether there may be more of those than counted, which is counted among the newest
155	/// changes only.
156	pub here_alone_more: bool,
157}
158
159impl Default for ChangeCopies {
160	fn default() -> Self {
161		Self {
162			needs: crate::Needs::CRITICAL,
163			disks: 0,
164			away: 0,
165			archived: 0,
166			here_alone: 0,
167			here_alone_more: false,
168		}
169	}
170}
171
172/// Sealed blobs, or contents, each with when a replica last checked it, in milliseconds
173/// since 1970, or 0 if it never did.
174pub(crate) type Checked = BTreeMap<Hash, u64>;
175
176/// What another replica's latest account of a space says it holds.
177pub(crate) struct Listed {
178	/// Its disk.
179	pub(crate) disk: Hash,
180	/// Its sealed blobs.
181	pub(crate) sealed: Checked,
182	/// The contents of its unchanged plain copies.
183	pub(crate) plain: Checked,
184}
185
186/// One author's pages about a backup, opened: its head, with when it was issued, and its
187/// sealed blobs.
188type PagesAbout = (Option<(BackupHead, u64)>, Vec<(Hash, u64)>);
189
190/// The latest account of a backup in a space, opened.
191pub(crate) struct BackupAccount {
192	/// Its head.
193	pub(crate) head: BackupHead,
194	/// When its head was issued.
195	pub(crate) issued: u64,
196	/// Its sealed blobs, with when each was last checked.
197	pub(crate) blobs: Vec<(Hash, u64)>,
198}
199
200/// One replica's account, opened.
201#[derive(Default)]
202struct Account {
203	head: Option<(Head, u64)>,
204	blobs: Vec<(Hash, u64)>,
205	copies: Vec<(EntityId, Hash, u64)>,
206}
207
208/// The copies of a space by disk: this replica's as it holds them now, and the others' as
209/// their accounts say.
210pub(crate) struct Copies {
211	/// The disks, this replica's first.
212	pub(crate) disks: Vec<Disk>,
213	/// For each sealed hash, the disks that hold it, this replica's as it holds it now, with
214	/// when each last checked it, or 0 if it never did.
215	by_sealed: BTreeMap<Hash, Vec<(usize, u64)>>,
216	/// For each file and content, the disks that hold an unchanged plain copy, this replica's
217	/// as it holds it now, with when each last checked it, or 0 if it never did.
218	by_copy: BTreeMap<(EntityId, Hash), Vec<(usize, u64)>>,
219	/// The heads of each other replica, with its disk.
220	heads: Vec<(usize, Vec<ChangeId>)>,
221	/// Copies last checked before this time count no longer, in milliseconds since 1970.
222	since: u64,
223}
224
225impl Copies {
226	/// This replica's disk.
227	pub(crate) const OWN: usize = 0;
228
229	/// The disks that hold a copy of the content `content` of a file, whose entities, those
230	/// merged into it included, are `members`: those that hold one of its sealed hashes,
231	/// `sealed`, or an unchanged plain copy of it, each with when it last checked one.
232	fn checked_on(
233		&self,
234		sealed: &[Hash],
235		(members, content): (&[EntityId], Option<Hash>),
236	) -> BTreeMap<usize, u64> {
237		let mut disks: BTreeMap<usize, u64> = BTreeMap::new();
238		let mut note = |disk: usize, checked: u64| {
239			let latest = disks.entry(disk).or_insert(0);
240			*latest = (*latest).max(checked);
241		};
242		for each in sealed {
243			for (disk, checked) in self.by_sealed.get(each).into_iter().flatten() {
244				note(*disk, *checked);
245			}
246		}
247		if let Some(content) = content {
248			for member in members {
249				for (disk, checked) in self.by_copy.get(&(*member, content)).into_iter().flatten() {
250					note(*disk, *checked);
251				}
252			}
253		}
254		disks
255	}
256
257	/// The disks whose copies of a file count, as [`Copies::checked_on`] finds them: those
258	/// checked in the last 8 weeks; and the disks that hold copies checked before only, which
259	/// do not count.
260	pub(crate) fn holding(
261		&self,
262		sealed: &[Hash],
263		of: (&[EntityId], Option<Hash>),
264	) -> (BTreeSet<usize>, BTreeSet<usize>) {
265		let (counting, old): (Vec<_>, Vec<_>) = self
266			.checked_on(sealed, of)
267			.into_iter()
268			.partition(|(_, checked)| *checked >= self.since);
269		(
270			counting.into_iter().map(|(disk, _)| disk).collect(),
271			old.into_iter().map(|(disk, _)| disk).collect(),
272		)
273	}
274
275	/// Whether this replica holds an unchanged plain copy of the content of a file whose
276	/// entities are `members`, which the last check did not find damaged.
277	pub(crate) fn plain_here(&self, members: &[EntityId], content: Option<Hash>) -> bool {
278		content.is_some_and(|content| {
279			members.iter().any(|member| {
280				self.by_copy
281					.get(&(*member, content))
282					.is_some_and(|disks| disks.iter().any(|(disk, _)| *disk == Self::OWN))
283			})
284		})
285	}
286
287	/// How many of the disks are away from home, and how many are archive nodes'.
288	pub(crate) fn marked(&self, disks: &BTreeSet<usize>) -> (usize, usize) {
289		let away = disks.iter().filter(|disk| self.disks[**disk].away).count();
290		let archived = disks
291			.iter()
292			.filter(|disk| self.disks[**disk].archive)
293			.count();
294		(away, archived)
295	}
296}
297
298/// A disk's ID in a space: its name hashed with a key derived from the space's ID, so that
299/// replicas on one disk show one ID within a space, and a disk's IDs in two spaces cannot be
300/// linked; a replica whose disk nothing names is a disk of its own.
301pub(crate) fn disk_id(space: SpaceId, name: Option<&[u8]>, replica: &VerifyingKey) -> Hash {
302	let key = blake3::derive_key(DISK_CONTEXT, space.as_bytes());
303	let mut hasher = blake3::Hasher::new_keyed(&key);
304	match name {
305		Some(name) => hasher.update(b"disk\0").update(name),
306		None => hasher.update(b"replica\0").update(replica.as_bytes()),
307	};
308	Hash::of(hasher.finalize().as_bytes())
309}
310
311/// A page with nothing on it, as a replica issues for a page it no longer has anything for.
312fn empty(kind: PageKind) -> Option<PageBody> {
313	match kind {
314		PageKind::Head => None,
315		PageKind::Blobs(byte) => Some(PageBody::Blobs(byte, Vec::new())),
316		PageKind::Copies(byte) => Some(PageBody::Copies(byte, Vec::new())),
317	}
318}
319
320impl Library {
321	/// How the person marked one of their devices, in the personal space: as an archive node
322	/// or an everyday device, and whether it is kept away from home.
323	///
324	/// # Errors
325	///
326	/// Returns an error if the personal space cannot be read.
327	pub fn device_marks(&self, device: EntityId) -> Result<DeviceMarks, NodeError> {
328		let state = self.space(self.info.personal)?.stored.log().state();
329		let role = state
330			.last_written(device, &DEVICE_ROLE)?
331			.and_then(|statement| statement.value.as_text().and_then(DeviceRole::from_name))
332			.unwrap_or_default();
333		let away = state
334			.last_written(device, &AWAY)?
335			.is_some_and(|statement| statement.value == Value::Boolean(true));
336		let number = |field| -> Result<Option<u64>, NodeError> {
337			Ok(state
338				.last_written(device, field)?
339				.and_then(|statement| match statement.value {
340					Value::Integer(number) => u64::try_from(number).ok(),
341					_ => None,
342				}))
343		};
344		Ok(DeviceMarks {
345			role,
346			away,
347			keeps: number(&KEEPS_UP_TO)?,
348			waits: number(&WAITS)?,
349		})
350	}
351
352	/// Marks one of the person's devices, in the personal space: as an archive node or an
353	/// everyday device, as kept away from home or not, and with how many bytes of files it
354	/// keeps as an everyday device, or the default. Its replicas tell the others so at
355	/// their next syncs ([technical design: where the copies are]).
356	///
357	/// [technical design: where the copies are]: ../../../../docs/Technical-design.md#96-where-the-copies-are
358	///
359	/// # Errors
360	///
361	/// Returns [`NodeError::WhichDevice`] if `device` is no device of the personal space, and
362	/// another error if the change cannot be saved.
363	pub fn set_device_marks(
364		&mut self,
365		device: EntityId,
366		marks: DeviceMarks,
367		wall_millis: u64,
368		rng: &mut impl CryptoRng,
369	) -> Result<(), NodeError> {
370		let personal = self.info.personal;
371		let state = self.space(personal)?.stored.log().state();
372		let device = state.canonical(device)?;
373		if state.is_deleted(device)? || !state.types(device)?.contains(&DEVICE) {
374			return Err(NodeError::WhichDevice(format!(
375				"{device} is no device of yours"
376			)));
377		}
378		let mut operations = Vec::new();
379		for (field, value) in [
380			(DEVICE_ROLE, Value::Text(marks.role.as_str().to_owned())),
381			(AWAY, Value::Boolean(marks.away)),
382		] {
383			// The field's last writer wins: a new value replaces every value before it.
384			let shown = state
385				.last_written(device, &field)?
386				.map(|statement| statement.value.clone());
387			let unmarked = match &value {
388				Value::Text(role) => role == DeviceRole::Everyday.as_str(),
389				_ => value == Value::Boolean(false),
390			};
391			if shown.as_ref() == Some(&value) || (shown.is_none() && unmarked) {
392				continue;
393			}
394			let replaced: Vec<StatementId> = state
395				.current(device, &field)?
396				.iter()
397				.map(|statement| statement.id)
398				.collect();
399			operations.push(Operation::replace(
400				Statement::new(StatementId::random(rng), device, field, value),
401				replaced,
402			));
403		}
404		// The size and the wait, or the defaults without them: their values go.
405		for (field, number) in [(KEEPS_UP_TO, marks.keeps), (WAITS, marks.waits)] {
406			let values: Vec<StatementId> = state
407				.current(device, &field)?
408				.iter()
409				.map(|statement| statement.id)
410				.collect();
411			let shown = state
412				.last_written(device, &field)?
413				.map(|statement| statement.value.clone());
414			match number.map(|number| Value::Integer(i64::try_from(number).unwrap_or(i64::MAX))) {
415				Some(value) if shown.as_ref() != Some(&value) => {
416					operations.push(Operation::replace(
417						Statement::new(StatementId::random(rng), device, field, value),
418						values,
419					));
420				}
421				None if !values.is_empty() => {
422					operations.push(Operation::retract(device, values));
423				}
424				_ => {}
425			}
426		}
427		if operations.is_empty() {
428			return Ok(());
429		}
430		self.commit(personal, operations, wall_millis, rng)?;
431		// This device's wait holds at once if it is longer, and so does keeping what purges
432		// destroy.
433		if device == self.info.device {
434			self.refresh_wait(wall_millis)?;
435		}
436		Ok(())
437	}
438
439	/// Whether the replica whose key is `key` counts in a space: listed there, and neither
440	/// revoked nor removed.
441	pub(crate) fn counts_in(&self, space: SpaceId, key: &VerifyingKey) -> Result<bool, NodeError> {
442		let open = self.space(space)?;
443		let log = open.stored.log();
444		Ok(log.is_listed(key, &open.keys)?
445			&& !log.is_revoked(key, &open.keys)?
446			&& !log.is_removed(key, &open.keys)?)
447	}
448
449	/// This replica's pages of its account of a space, as the log file keeps them, opened,
450	/// by kind, with when each was issued.
451	fn own_pages(&self, space: SpaceId) -> Result<BTreeMap<PageKind, (PageBody, u64)>, NodeError> {
452		let own = self.replica.signing.verifying_key();
453		let open = self.space(space)?;
454		let mut pages = BTreeMap::new();
455		for stored in open.stored.account_pages()? {
456			if stored.author != *own.as_bytes() {
457				continue;
458			}
459			if let Some(body) = AccountPage::from_bytes(&stored.bytes)
460				.ok()
461				.and_then(|page| page.open(&open.keys).ok())
462			{
463				pages.insert(body.kind(), (body, stored.issued));
464			}
465		}
466		Ok(pages)
467	}
468
469	/// The disk that this replica is on, by its ID in a space, as its folder's drive tells,
470	/// read anew each time. A name read later than a guess replaces the guess.
471	pub(crate) fn own_disk(&self, space: SpaceId) -> Hash {
472		disk_id(
473			space,
474			place::disk_name(&self.directory).as_deref(),
475			&self.replica.signing.verifying_key(),
476		)
477	}
478
479	/// What this replica holds of a space now, as the pages of its account tell it at
480	/// `wall_millis`: the head, and each page that lists something.
481	fn own_bodies(
482		&self,
483		space: SpaceId,
484		disk: Hash,
485		wall_millis: u64,
486	) -> Result<Vec<PageBody>, NodeError> {
487		let open = self.space(space)?;
488		let marks = self.device_marks(self.info.device)?;
489		let plain = self.plain_state(space)?;
490		let (damaged, unrepaired) = self.own_damage(space, &plain, wall_millis)?;
491		let mut bodies = vec![PageBody::Head(Head {
492			disk,
493			role: marks.role,
494			away: marks.away,
495			heads: open.stored.log().heads()?.into_iter().collect(),
496			damaged,
497			unrepaired,
498			waits: self
499				.wait_in_force(wall_millis)?
500				.div_ceil(super::waiting::DAY),
501		})];
502		let checks = self.blob_checks(space)?;
503		let mut blobs: BTreeMap<u8, Vec<(Hash, u64)>> = BTreeMap::new();
504		for sealed in open.stored.sealed_blobs()? {
505			let checked = checks.get(&sealed).copied().unwrap_or(0);
506			blobs
507				.entry(sealed.digest()[0])
508				.or_default()
509				.push((sealed, checked));
510		}
511		bodies.extend(
512			blobs
513				.into_iter()
514				.map(|(byte, blobs)| PageBody::Blobs(byte, blobs)),
515		);
516		let mut copies: BTreeMap<u8, Vec<(EntityId, Hash, u64)>> = BTreeMap::new();
517		for ((file, content), checked) in plain.copies() {
518			copies
519				.entry(file.as_bytes()[0])
520				.or_default()
521				.push((file, content, checked));
522		}
523		bodies.extend(
524			copies
525				.into_iter()
526				.map(|(byte, copies)| PageBody::Copies(byte, copies)),
527		);
528		Ok(bodies)
529	}
530
531	/// Brings this replica's account of a space up to date: issues each page whose content
532	/// changed since it last issued it, a page it no longer has anything for as an empty
533	/// one, at the wall clock `wall_millis` or just after its last page of that kind, and
534	/// keeps them in the log file. Returns how many pages it issued.
535	///
536	/// # Errors
537	///
538	/// Returns an error if the space cannot be read, or the pages cannot be saved.
539	pub(crate) fn refresh_account(
540		&mut self,
541		space: SpaceId,
542		wall_millis: u64,
543		rng: &mut impl CryptoRng,
544	) -> Result<usize, NodeError> {
545		// A sync with each of several replicas, one after the other, finds the same.
546		let mark = self.state_mark(space)?;
547		if self
548			.accounts_refreshed
549			.borrow()
550			.get(&space)
551			.is_some_and(|(at_mark, at)| {
552				*at_mark == mark && wall_millis.saturating_sub(*at) < REFRESHED_FOR
553			}) {
554			return Ok(0);
555		}
556		let count = self.issue_account(space, wall_millis, rng)?;
557		self.accounts_refreshed
558			.borrow_mut()
559			.insert(space, (mark, wall_millis));
560		Ok(count)
561	}
562
563	/// Issues each page of this replica's account of a space whose content changed, as
564	/// [`Library::refresh_account`] says.
565	fn issue_account(
566		&mut self,
567		space: SpaceId,
568		wall_millis: u64,
569		rng: &mut impl CryptoRng,
570	) -> Result<usize, NodeError> {
571		let issued_before: BTreeMap<u16, u64> = {
572			let own = self.replica.signing.verifying_key();
573			self.space(space)?
574				.stored
575				.account_page_ids()?
576				.into_iter()
577				.filter(|stored| stored.author == *own.as_bytes())
578				.map(|stored| (stored.page, stored.issued))
579				.collect()
580		};
581		let pages = self.own_pages(space)?;
582		let disk = self.own_disk(space);
583		let mut bodies: BTreeMap<PageKind, PageBody> = self
584			.own_bodies(space, disk, wall_millis)?
585			.into_iter()
586			.map(|body| (body.kind(), body))
587			.collect();
588		for (kind, (body, _)) in &pages {
589			if !bodies.contains_key(kind)
590				&& let Some(nothing) = empty(*kind)
591				&& *body != nothing
592			{
593				bodies.insert(*kind, nothing);
594			}
595		}
596		let author = *self.replica.signing.verifying_key().as_bytes();
597		let mut issued = Vec::new();
598		let open = self.space(space)?;
599		for (kind, body) in bodies {
600			if pages.get(&kind).is_some_and(|(kept, _)| *kept == body) {
601				continue;
602			}
603			let at = issued_before
604				.get(&kind.number())
605				.map_or(wall_millis, |last| wall_millis.max(last.saturating_add(1)));
606			let page =
607				AccountPage::issue(space, &open.keys, &self.replica.signing, (at, &body), rng);
608			let bytes = page.to_bytes();
609			issued.push(StoredPage {
610				author,
611				backup: None,
612				page: kind.number(),
613				issued: at,
614				id: Hash::of(&bytes),
615				bytes,
616			});
617		}
618		let count = issued.len();
619		self.spaces
620			.get_mut(&space)
621			.ok_or(NodeError::NoSpace(space))?
622			.stored
623			.save_account_pages(&issued)?;
624		Ok(count)
625	}
626
627	/// Checks a page of an account that another replica sent: whether its author signed it,
628	/// it is of this space, its author is a replica of the space that counts there and not
629	/// this one, and it is later than the one of that page that the log file keeps. Returns
630	/// it as the log file keeps it if so, for [`Library::save_accounts`].
631	///
632	/// # Errors
633	///
634	/// Returns an error if the space cannot be read.
635	pub(crate) fn check_account(
636		&self,
637		space: SpaceId,
638		bytes: &[u8],
639	) -> Result<Option<StoredPage>, NodeError> {
640		let Ok(page) = AccountPage::from_bytes(bytes) else {
641			return Ok(None);
642		};
643		if page.space() != space
644			|| *page.author() == self.replica.signing.verifying_key()
645			|| !self.counts_in(space, page.author())?
646		{
647			return Ok(None);
648		}
649		let stored = StoredPage {
650			author: *page.author().as_bytes(),
651			backup: page.about().map(|backup| *backup.as_bytes()),
652			page: page.kind().number(),
653			issued: page.issued(),
654			id: Hash::of(bytes),
655			bytes: bytes.to_vec(),
656		};
657		let open = self.space(space)?;
658		let kept = if stored.backup.is_some() {
659			open.stored.backup_account_page_ids()?
660		} else {
661			open.stored.account_page_ids()?
662		};
663		// One replica speaks for a few backups at most, so that none fills the others' disks
664		// with pages about backups it made up.
665		if let Some(backup) = stored.backup {
666			let spoken_for: BTreeSet<[u8; 16]> = kept
667				.iter()
668				.filter(|kept| kept.author == stored.author)
669				.filter_map(|kept| kept.backup)
670				.collect();
671			if !spoken_for.contains(&backup) && spoken_for.len() >= BACKUPS_PER_REPLICA {
672				return Ok(None);
673			}
674		}
675		let later = kept
676			.into_iter()
677			.find(|kept| {
678				kept.author == stored.author
679					&& kept.backup == stored.backup
680					&& kept.page == stored.page
681			})
682			.is_none_or(|kept| (stored.issued, stored.id) > (kept.issued, kept.id));
683		Ok(later.then_some(stored))
684	}
685
686	/// Keeps pages of accounts of a space that [`Library::check_account`] passed, together:
687	/// each that is still later than the one of its page that the log file keeps.
688	///
689	/// # Errors
690	///
691	/// Returns an error if the pages cannot be saved.
692	pub(crate) fn save_accounts(
693		&mut self,
694		space: SpaceId,
695		pages: &[StoredPage],
696	) -> Result<usize, NodeError> {
697		Ok(self
698			.spaces
699			.get_mut(&space)
700			.ok_or(NodeError::NoSpace(space))?
701			.stored
702			.save_account_pages(pages)?)
703	}
704
705	/// The pages of accounts of a space that a sync passes on, by the hash of each page's
706	/// encoding, with when it was issued: this replica's, and those of the replicas that
707	/// count in the space.
708	///
709	/// # Errors
710	///
711	/// Returns an error if the space cannot be read.
712	pub(crate) fn account_holdings(&self, space: SpaceId) -> Result<Vec<(Hash, u64)>, NodeError> {
713		let own = *self.replica.signing.verifying_key().as_bytes();
714		let mut counting: BTreeMap<[u8; 32], bool> = BTreeMap::new();
715		let mut holdings = Vec::new();
716		let open = self.space(space)?;
717		let pages = open
718			.stored
719			.account_page_ids()?
720			.into_iter()
721			.chain(open.stored.backup_account_page_ids()?);
722		for stored in pages {
723			let counts = if stored.author == own {
724				true
725			} else if let Some(counts) = counting.get(&stored.author) {
726				*counts
727			} else {
728				let counts = VerifyingKey::from_bytes(&stored.author)
729					.map_or(Ok(false), |key| self.counts_in(space, &key))?;
730				counting.insert(stored.author, counts);
731				counts
732			};
733			if counts {
734				holdings.push((stored.id, stored.issued));
735			}
736		}
737		Ok(holdings)
738	}
739
740	/// The encoding of a page of an account of a space that the log file keeps, by the hash
741	/// of its encoding.
742	///
743	/// # Errors
744	///
745	/// Returns an error if the space cannot be read.
746	pub(crate) fn account_page(
747		&self,
748		space: SpaceId,
749		id: &Hash,
750	) -> Result<Option<Vec<u8>>, NodeError> {
751		Ok(self.space(space)?.stored.account_page(id)?)
752	}
753
754	/// The copies of a space by disk: what this replica holds now, and what the latest pages
755	/// of the accounts of the replicas that count in the space say they hold, as of
756	/// `wall_millis`, before which copies checked more than 8 weeks earlier count no longer.
757	///
758	/// # Errors
759	///
760	/// Returns an error if the space cannot be read.
761	pub(crate) fn copies_by_disk(
762		&self,
763		space: SpaceId,
764		wall_millis: u64,
765	) -> Result<Copies, NodeError> {
766		let own = self.replica.signing.verifying_key();
767		let pages = self.own_pages(space)?;
768		let own_disk = self.own_disk(space);
769		let marks = self.device_marks(self.info.device)?;
770		let plain = self.plain_state(space)?;
771		let (damaged, unrepaired) = self.own_damage(space, &plain, wall_millis)?;
772		let mut replicas: BTreeMap<[u8; 32], crate::Replica> = BTreeMap::new();
773		for replica in self.replicas()?.into_iter().chain(self.peers()?) {
774			if let Some(key) = replica.signing {
775				replicas.entry(*key.as_bytes()).or_insert(replica);
776			}
777		}
778		let named = |key: &[u8; 32], this: bool| {
779			let replica = replicas.get(key);
780			DiskReplica {
781				replica: replica.map(|replica| replica.id),
782				name: replica.and_then(|replica| replica.name.clone()),
783				device: replica.and_then(|replica| replica.device_name.clone()),
784				member: replica.and_then(|replica| replica.member.clone()),
785				this,
786			}
787		};
788		let mut copies = Copies {
789			disks: vec![Disk {
790				id: own_disk,
791				here: true,
792				replicas: vec![named(own.as_bytes(), true)],
793				archive: marks.role == DeviceRole::Archive,
794				away: marks.away,
795				issued: pages.get(&PageKind::Head).map(|(_, issued)| *issued),
796				damaged,
797				unrepaired,
798				backups: Vec::new(),
799			}],
800			by_sealed: BTreeMap::new(),
801			by_copy: BTreeMap::new(),
802			heads: Vec::new(),
803			since: wall_millis.saturating_sub(COUNTS_FOR_MILLIS),
804		};
805		self.add_own_copies(space, &plain, &mut copies)?;
806		let accounts = self.other_accounts(space)?;
807		let mut by_id: BTreeMap<Hash, usize> = BTreeMap::from([(own_disk, Copies::OWN)]);
808		for (author, account) in accounts {
809			// Without its head, an account says nothing of where its copies are.
810			let Some((head, issued)) = account.head else {
811				continue;
812			};
813			let index = *by_id.entry(head.disk).or_insert_with(|| {
814				copies.disks.push(Disk {
815					id: head.disk,
816					here: false,
817					replicas: Vec::new(),
818					archive: true,
819					away: true,
820					issued: None,
821					damaged: 0,
822					unrepaired: 0,
823					backups: Vec::new(),
824				});
825				copies.disks.len() - 1
826			});
827			let disk = &mut copies.disks[index];
828			disk.replicas.push(named(&author, false));
829			disk.archive &= head.role == DeviceRole::Archive;
830			disk.away &= head.away;
831			disk.issued = disk.issued.max(Some(issued));
832			disk.damaged = disk.damaged.saturating_add(head.damaged);
833			disk.unrepaired = disk.unrepaired.saturating_add(head.unrepaired);
834			for (sealed, checked) in account.blobs {
835				copies
836					.by_sealed
837					.entry(sealed)
838					.or_default()
839					.push((index, checked));
840			}
841			for (file, content, checked) in account.copies {
842				copies
843					.by_copy
844					.entry((file, content))
845					.or_default()
846					.push((index, checked));
847			}
848			copies.heads.push((index, head.heads));
849		}
850		self.add_backup_copies(space, &mut copies, &mut by_id)?;
851		Ok(copies)
852	}
853
854	/// Adds the backups of a space to `copies`, each as the replica that updated it last
855	/// says: a disk too, which keeps what an archive node keeps; `by_id` holds the index of
856	/// each disk by its ID.
857	fn add_backup_copies(
858		&self,
859		space: SpaceId,
860		copies: &mut Copies,
861		by_id: &mut BTreeMap<Hash, usize>,
862	) -> Result<(), NodeError> {
863		// The backups, each as the replica that updated it last says: a disk too, which keeps
864		// what an archive node keeps.
865		let backup_names: BTreeMap<EntityId, String> = self
866			.backups()?
867			.into_iter()
868			.map(|backup| (backup.id, backup.name))
869			.collect();
870		for (backup, account) in self.backup_accounts(space)? {
871			// One that the person removed no longer counts, whatever pages about it remain.
872			if self.backup_forgotten(backup)? {
873				continue;
874			}
875			let head = account.head;
876			let index = *by_id.entry(head.disk).or_insert_with(|| {
877				copies.disks.push(Disk {
878					id: head.disk,
879					here: false,
880					replicas: Vec::new(),
881					archive: true,
882					away: true,
883					issued: None,
884					damaged: 0,
885					unrepaired: 0,
886					backups: Vec::new(),
887				});
888				copies.disks.len() - 1
889			});
890			let disk = &mut copies.disks[index];
891			disk.backups.push(DiskBackup {
892				backup,
893				name: backup_names.get(&backup).cloned(),
894				update: head.update,
895			});
896			disk.away &= head.away;
897			disk.issued = disk.issued.max(Some(account.issued));
898			disk.damaged = disk.damaged.saturating_add(head.damaged);
899			disk.unrepaired = disk.unrepaired.saturating_add(head.unrepaired);
900			for (sealed, checked) in account.blobs {
901				copies
902					.by_sealed
903					.entry(sealed)
904					.or_default()
905					.push((index, checked));
906			}
907			copies.heads.push((index, head.heads));
908		}
909		Ok(())
910	}
911
912	/// The latest account of each backup of a space, as the replica that counts there and
913	/// tells of its latest update says it, this one included: its head, when that was
914	/// issued, and its sealed blobs with when each was last checked.
915	pub(crate) fn backup_accounts(
916		&self,
917		space: SpaceId,
918	) -> Result<BTreeMap<EntityId, BackupAccount>, NodeError> {
919		let own = *self.replica.signing.verifying_key().as_bytes();
920		let open = self.space(space)?;
921		// Each author's pages about each backup, opened.
922		let mut by_author: BTreeMap<(EntityId, [u8; 32]), PagesAbout> = BTreeMap::new();
923		let mut counting: BTreeMap<[u8; 32], bool> = BTreeMap::new();
924		for stored in open.stored.backup_account_pages()? {
925			let Some(backup) = stored.backup.map(EntityId::from_bytes) else {
926				continue;
927			};
928			let counts = if stored.author == own {
929				true
930			} else if let Some(counts) = counting.get(&stored.author) {
931				*counts
932			} else {
933				let counts = VerifyingKey::from_bytes(&stored.author)
934					.map_or(Ok(false), |key| self.counts_in(space, &key))?;
935				counting.insert(stored.author, counts);
936				counts
937			};
938			let Some(body) = counts
939				.then(|| AccountPage::from_bytes(&stored.bytes).ok())
940				.flatten()
941				.filter(|page| {
942					page.author().as_bytes() == &stored.author && page.about() == Some(backup)
943				})
944				.and_then(|page| page.open(&open.keys).ok())
945			else {
946				continue;
947			};
948			let entry = by_author.entry((backup, stored.author)).or_default();
949			match body {
950				PageBody::BackupHead(head) => entry.0 = Some((head, stored.issued)),
951				PageBody::Blobs(_, blobs) => entry.1.extend(blobs),
952				PageBody::Head(_) | PageBody::Copies(..) => {}
953			}
954		}
955		let mut accounts: BTreeMap<EntityId, BackupAccount> = BTreeMap::new();
956		for ((backup, _), (head, blobs)) in by_author {
957			let Some((head, issued)) = head else {
958				continue;
959			};
960			let later = accounts
961				.get(&backup)
962				.is_none_or(|kept| (head.update, issued) > (kept.head.update, kept.issued));
963			if later {
964				accounts.insert(
965					backup,
966					BackupAccount {
967						head,
968						issued,
969						blobs,
970					},
971				);
972			}
973		}
974		Ok(accounts)
975	}
976
977	/// Issues the pages of the account of a backup in a space whose content changed since
978	/// this replica last issued them, a page it no longer has anything for as an empty one,
979	/// at `wall_millis` or just after its last page of that kind, and keeps them in the log
980	/// file. Returns how many it issued.
981	pub(crate) fn issue_backup_account(
982		&mut self,
983		space: SpaceId,
984		backup: EntityId,
985		(head, blobs): (BackupHead, &BTreeMap<Hash, u64>),
986		wall_millis: u64,
987		rng: &mut impl CryptoRng,
988	) -> Result<usize, NodeError> {
989		let author = *self.replica.signing.verifying_key().as_bytes();
990		let id = *backup.as_bytes();
991		let open = self.space(space)?;
992		let mut before: BTreeMap<PageKind, (PageBody, u64)> = BTreeMap::new();
993		for stored in open.stored.backup_account_pages()? {
994			if stored.author != author || stored.backup != Some(id) {
995				continue;
996			}
997			if let Some(body) = AccountPage::from_bytes(&stored.bytes)
998				.ok()
999				.and_then(|page| page.open(&open.keys).ok())
1000			{
1001				before.insert(body.kind(), (body, stored.issued));
1002			}
1003		}
1004		// Each page later than the last of its kind that this replica issued, whether that
1005		// one opens or not.
1006		let last_issued: BTreeMap<u16, u64> = open
1007			.stored
1008			.backup_account_page_ids()?
1009			.into_iter()
1010			.filter(|stored| stored.author == author && stored.backup == Some(id))
1011			.map(|stored| (stored.page, stored.issued))
1012			.collect();
1013		let mut bodies: BTreeMap<PageKind, PageBody> =
1014			BTreeMap::from([(PageKind::Head, PageBody::BackupHead(head))]);
1015		let mut pages: BTreeMap<u8, Vec<(Hash, u64)>> = BTreeMap::new();
1016		for (sealed, checked) in blobs {
1017			pages
1018				.entry(sealed.digest()[0])
1019				.or_default()
1020				.push((*sealed, *checked));
1021		}
1022		for (byte, listed) in pages {
1023			bodies.insert(PageKind::Blobs(byte), PageBody::Blobs(byte, listed));
1024		}
1025		for (kind, (body, _)) in &before {
1026			if !bodies.contains_key(kind)
1027				&& let Some(nothing) = empty(*kind)
1028				&& *body != nothing
1029			{
1030				bodies.insert(*kind, nothing);
1031			}
1032		}
1033		let mut issued = Vec::new();
1034		for (kind, body) in bodies {
1035			if before.get(&kind).is_some_and(|(kept, _)| *kept == body) {
1036				continue;
1037			}
1038			let at = last_issued
1039				.get(&kind.number())
1040				.map_or(wall_millis, |last| wall_millis.max(last.saturating_add(1)));
1041			let page = AccountPage::issue_about(
1042				space,
1043				&open.keys,
1044				&self.replica.signing,
1045				backup,
1046				(at, &body),
1047				rng,
1048			);
1049			let bytes = page.to_bytes();
1050			issued.push(StoredPage {
1051				author,
1052				backup: Some(id),
1053				page: kind.number(),
1054				issued: at,
1055				id: Hash::of(&bytes),
1056				bytes,
1057			});
1058		}
1059		let count = issued.len();
1060		self.spaces
1061			.get_mut(&space)
1062			.ok_or(NodeError::NoSpace(space))?
1063			.stored
1064			.save_account_pages(&issued)?;
1065		Ok(count)
1066	}
1067
1068	/// The latest accounts of the replicas that count in a space, but this one's, opened.
1069	fn other_accounts(&self, space: SpaceId) -> Result<BTreeMap<[u8; 32], Account>, NodeError> {
1070		self.other_accounts_where(space, |_, _| true)
1071	}
1072
1073	/// The heads of the latest accounts of the other replicas that count in a space, by
1074	/// their keys: their pages of blobs and copies are not read.
1075	pub(crate) fn other_heads(&self, space: SpaceId) -> Result<Vec<([u8; 32], Head)>, NodeError> {
1076		Ok(self
1077			.other_accounts_where(space, |_, page| page == 0)?
1078			.into_iter()
1079			.filter_map(|(author, account)| account.head.map(|(head, _)| (author, head)))
1080			.collect())
1081	}
1082
1083	/// Whether a device of a space is an archive node: this replica's, as the person marked
1084	/// it, or another's, as the latest account of a replica of the space on it says.
1085	pub(crate) fn has_archive_node(&self, space: SpaceId) -> Result<bool, NodeError> {
1086		if self.device_marks(self.info.device)?.role == DeviceRole::Archive {
1087			return Ok(true);
1088		}
1089		let head = PageKind::Head.number();
1090		Ok(self
1091			.other_accounts_where(space, |_, page| page == head)?
1092			.values()
1093			.any(|account| {
1094				account
1095					.head
1096					.as_ref()
1097					.is_some_and(|(head, _)| head.role == DeviceRole::Archive)
1098			}))
1099	}
1100
1101	/// The sealed blobs of a space that another replica's latest account lists, by its key;
1102	/// `None` if this replica keeps no account of it in the space.
1103	pub(crate) fn listed_blobs(
1104		&self,
1105		space: SpaceId,
1106		author: &VerifyingKey,
1107	) -> Result<Option<BTreeSet<Hash>>, NodeError> {
1108		let accounts = self.other_accounts_where(space, |of, _| of == author.as_bytes())?;
1109		Ok(accounts
1110			.get(author.as_bytes())
1111			.map(|account| account.blobs.iter().map(|(sealed, _)| *sealed).collect()))
1112	}
1113
1114	/// Whether each disk of the space's other replicas is an archive node's, by its ID, as the
1115	/// heads of their latest accounts say: only if every replica on it says that its device is
1116	/// one.
1117	pub(crate) fn archive_disks(&self, space: SpaceId) -> Result<BTreeMap<Hash, bool>, NodeError> {
1118		let head = PageKind::Head.number();
1119		let mut disks = BTreeMap::new();
1120		for account in self
1121			.other_accounts_where(space, |_, page| page == head)?
1122			.into_values()
1123		{
1124			if let Some((head, _)) = account.head {
1125				let archive = disks.entry(head.disk).or_insert(true);
1126				*archive &= head.role == DeviceRole::Archive;
1127			}
1128		}
1129		Ok(disks)
1130	}
1131
1132	/// What the latest accounts of these other replicas of a space, by their keys, say they
1133	/// hold: for each that sent its head, its disk, its sealed blobs with when it last checked
1134	/// each, and, if `plain` asks, the contents of its unchanged plain copies, as originals
1135	/// kept where they were found, with when it last checked one of each; 0 if it never did.
1136	pub(crate) fn listed_by(
1137		&self,
1138		space: SpaceId,
1139		authors: &BTreeSet<[u8; 32]>,
1140		plain: bool,
1141	) -> Result<BTreeMap<[u8; 32], Listed>, NodeError> {
1142		let copies = PageKind::Copies(0).number();
1143		Ok(self
1144			.other_accounts_where(space, |author, page| {
1145				authors.contains(author) && (plain || page < copies)
1146			})?
1147			.into_iter()
1148			.filter_map(|(author, account)| {
1149				let (head, _) = account.head?;
1150				let mut plain: Checked = BTreeMap::new();
1151				for (_, content, checked) in account.copies {
1152					let latest = plain.entry(content).or_insert(0);
1153					*latest = (*latest).max(checked);
1154				}
1155				Some((
1156					author,
1157					Listed {
1158						disk: head.disk,
1159						sealed: account.blobs.into_iter().collect(),
1160						plain,
1161					},
1162				))
1163			})
1164			.collect())
1165	}
1166
1167	/// The latest accounts of a space's other replicas that count there, of the pages that
1168	/// `keep` keeps, by their authors' keys and the pages' numbers.
1169	fn other_accounts_where(
1170		&self,
1171		space: SpaceId,
1172		keep: impl Fn(&[u8; 32], u16) -> bool,
1173	) -> Result<BTreeMap<[u8; 32], Account>, NodeError> {
1174		let own = self.replica.signing.verifying_key();
1175		let open = self.space(space)?;
1176		let mut accounts: BTreeMap<[u8; 32], Account> = BTreeMap::new();
1177		let mut counting: BTreeMap<[u8; 32], bool> = BTreeMap::new();
1178		for stored in open.stored.account_pages()? {
1179			if stored.author == *own.as_bytes() || !keep(&stored.author, stored.page) {
1180				continue;
1181			}
1182			let counts = if let Some(counts) = counting.get(&stored.author) {
1183				*counts
1184			} else {
1185				let counts = VerifyingKey::from_bytes(&stored.author)
1186					.map_or(Ok(false), |key| self.counts_in(space, &key))?;
1187				counting.insert(stored.author, counts);
1188				counts
1189			};
1190			let Some(body) = counts
1191				.then(|| AccountPage::from_bytes(&stored.bytes).ok())
1192				.flatten()
1193				.filter(|page| page.author().as_bytes() == &stored.author)
1194				.and_then(|page| page.open(&open.keys).ok())
1195			else {
1196				continue;
1197			};
1198			let account = accounts.entry(stored.author).or_default();
1199			match body {
1200				PageBody::Head(head) => account.head = Some((head, stored.issued)),
1201				PageBody::Blobs(_, blobs) => account.blobs.extend(blobs),
1202				PageBody::Copies(_, entries) => account.copies.extend(entries),
1203				PageBody::BackupHead(_) => {}
1204			}
1205		}
1206		Ok(accounts)
1207	}
1208
1209	/// When this replica last read each sealed blob of a space in full and found it intact: as
1210	/// the space records it, or as another of the replica's spaces does, whichever is later,
1211	/// as its spaces share one file of each blob. A blob whose key came to a space after its
1212	/// file, as the new space of a move, so counts as checked when its file last was.
1213	pub(crate) fn blob_checks(&self, space: SpaceId) -> Result<BTreeMap<Hash, u64>, NodeError> {
1214		let mut checks = self.space(space)?.stored.checks()?;
1215		for (&other, open) in &self.spaces {
1216			if other == space {
1217				continue;
1218			}
1219			for (sealed, at) in open.stored.checks()? {
1220				if let Some(checked) = checks.get_mut(&sealed) {
1221					*checked = (*checked).max(at);
1222				} else if open.stored.holds_sealed(&sealed) {
1223					checks.insert(sealed, at);
1224				}
1225			}
1226		}
1227		Ok(checks)
1228	}
1229
1230	/// Adds what this replica holds of a space now to `copies`, on its disk, each copy with
1231	/// when it was last checked; `plain` is its plain copies there.
1232	fn add_own_copies(
1233		&self,
1234		space: SpaceId,
1235		plain: &super::checking::PlainState,
1236		copies: &mut Copies,
1237	) -> Result<(), NodeError> {
1238		let open = self.space(space)?;
1239		let checks = self.blob_checks(space)?;
1240		for sealed in open.stored.sealed_blobs()? {
1241			let checked = checks.get(&sealed).copied().unwrap_or(0);
1242			copies
1243				.by_sealed
1244				.entry(sealed)
1245				.or_default()
1246				.push((Copies::OWN, checked));
1247		}
1248		for (copy, checked) in plain.copies() {
1249			copies
1250				.by_copy
1251				.entry(copy)
1252				.or_default()
1253				.push((Copies::OWN, checked));
1254		}
1255		Ok(())
1256	}
1257
1258	/// The disks that hold a copy of a file of a space, and how each holds it, as of
1259	/// `wall_millis`: this replica's, as it holds the file now, and the others' as their
1260	/// accounts say; a sealed copy before a plain one. A copy last checked more than 8 weeks
1261	/// before `wall_millis` does not count.
1262	///
1263	/// # Errors
1264	///
1265	/// Returns an error if the library has no such space, or the space cannot be read.
1266	pub fn copies_of(
1267		&self,
1268		space: SpaceId,
1269		file: EntityId,
1270		wall_millis: u64,
1271	) -> Result<Vec<FileCopy>, NodeError> {
1272		let copies = self.copies_by_disk(space, wall_millis)?;
1273		let open = self.space(space)?;
1274		let state = open.stored.log().state();
1275		let file = state.canonical(file)?;
1276		let content = state
1277			.current(file, &nibkeep_std::CONTENT)?
1278			.iter()
1279			.find_map(|statement| match statement.value {
1280				Value::Blob(hash) => Some(hash),
1281				_ => None,
1282			});
1283		let members: Vec<EntityId> = state.merged(file)?.into_iter().collect();
1284		let sealed = self.ordinary_sealed(space, content)?;
1285		let known = |checked: u64| Some(checked).filter(|checked| *checked > 0);
1286		let mut found: BTreeMap<usize, CopyHeld> = BTreeMap::new();
1287		for each in &sealed {
1288			for (disk, checked) in copies.by_sealed.get(each).into_iter().flatten() {
1289				let held = found
1290					.entry(*disk)
1291					.or_insert(CopyHeld::Sealed { checked: None });
1292				if let CopyHeld::Sealed { checked: before } = held {
1293					*before = (*before).max(known(*checked));
1294				}
1295			}
1296		}
1297		if let Some(content) = content {
1298			for member in &members {
1299				for (disk, checked) in copies
1300					.by_copy
1301					.get(&(*member, content))
1302					.into_iter()
1303					.flatten()
1304				{
1305					let held = found
1306						.entry(*disk)
1307						.or_insert(CopyHeld::InPlace { checked: None });
1308					if let CopyHeld::InPlace { checked: before } = held {
1309						*before = (*before).max(known(*checked));
1310					}
1311				}
1312			}
1313		}
1314		let latest = copies.checked_on(&sealed, (&members, content));
1315		Ok(found
1316			.into_iter()
1317			.map(|(disk, held)| FileCopy {
1318				disk: copies.disks[disk].clone(),
1319				held,
1320				counts: latest
1321					.get(&disk)
1322					.is_some_and(|checked| *checked >= copies.since),
1323			})
1324			.collect())
1325	}
1326
1327	/// The sealed hashes of a content's copies that every replica of the space can read: the
1328	/// ordinary ones whose keys this replica holds.
1329	pub(crate) fn ordinary_sealed(
1330		&self,
1331		space: SpaceId,
1332		content: Option<Hash>,
1333	) -> Result<Vec<Hash>, NodeError> {
1334		let Some(content) = content else {
1335			return Ok(Vec::new());
1336		};
1337		let log = self.space(space)?.stored.log();
1338		Ok(log
1339			.blob_keys(&content)
1340			.filter(|(sealed, _)| !log.is_secret_blob(sealed))
1341			.map(|(sealed, _)| *sealed)
1342			.collect())
1343	}
1344
1345	/// How the space's changes are held: how many disks hold every change this replica
1346	/// holds, how many of those are away or archive nodes', and how many of the newest
1347	/// changes are held on this replica's disk alone. A head of another replica that this
1348	/// one has not received hides what it builds on, so such a disk counts as holding less.
1349	///
1350	/// # Errors
1351	///
1352	/// Returns an error if the space cannot be read.
1353	pub(crate) fn change_copies(
1354		&self,
1355		space: SpaceId,
1356		copies: &Copies,
1357		needs: crate::Needs,
1358	) -> Result<ChangeCopies, NodeError> {
1359		self.change_copies_among(space, (copies, needs), NEWEST_LOOKED_AT)
1360	}
1361
1362	/// Each other disk's heads of a space, as `copies` give them, that this replica holds.
1363	fn other_heads_held(
1364		&self,
1365		space: SpaceId,
1366		copies: &Copies,
1367	) -> Result<BTreeMap<usize, Vec<ChangeId>>, NodeError> {
1368		let history = self.space(space)?.stored.log().history();
1369		let mut heads: BTreeMap<usize, Vec<ChangeId>> = BTreeMap::new();
1370		for (disk, theirs) in &copies.heads {
1371			if *disk == Copies::OWN {
1372				continue;
1373			}
1374			for head in theirs {
1375				if history.contains(*head)? {
1376					heads.entry(*disk).or_default().push(*head);
1377				}
1378			}
1379		}
1380		Ok(heads)
1381	}
1382
1383	/// The disks that hold every change of a space that this replica holds, this replica's
1384	/// own first: those whose heads, as `copies` give them, are each of this replica's heads
1385	/// or build on it.
1386	pub(crate) fn disks_holding_all(
1387		&self,
1388		space: SpaceId,
1389		copies: &Copies,
1390	) -> Result<BTreeSet<usize>, NodeError> {
1391		let log = self.space(space)?.stored.log();
1392		let mine: Vec<ChangeId> = log.heads()?.into_iter().collect();
1393		let mut holding = BTreeSet::from([Copies::OWN]);
1394		for (disk, theirs) in &self.other_heads_held(space, copies)? {
1395			let mut all = true;
1396			for head in &mine {
1397				let mut held = false;
1398				for their in theirs {
1399					if head == their || log.is_ancestor_of(*head, *their)? {
1400						held = true;
1401						break;
1402					}
1403				}
1404				if !held {
1405					all = false;
1406					break;
1407				}
1408			}
1409			if all {
1410				holding.insert(*disk);
1411			}
1412		}
1413		Ok(holding)
1414	}
1415
1416	/// How the space's changes are held, as [`Library::change_copies`] says, looking at the
1417	/// `newest` newest changes to count those held here alone.
1418	fn change_copies_among(
1419		&self,
1420		space: SpaceId,
1421		(copies, needs): (&Copies, crate::Needs),
1422		newest_looked_at: usize,
1423	) -> Result<ChangeCopies, NodeError> {
1424		let log = self.space(space)?.stored.log();
1425		let history = log.history();
1426		let mine: Vec<ChangeId> = log.heads()?.into_iter().collect();
1427		let heads = self.other_heads_held(space, copies)?;
1428		let holding = self.disks_holding_all(space, copies)?;
1429		let (away, archived) = copies.marked(&holding);
1430		// The newest changes, deepest first, and those of them that other disks hold.
1431		let mut newest: BTreeSet<ChangeId> = BTreeSet::new();
1432		let mut queue: BinaryHeap<(u64, ChangeId)> = BinaryHeap::new();
1433		for head in &mine {
1434			if let Some(depth) = history.depth(*head)? {
1435				queue.push((depth, *head));
1436			}
1437		}
1438		let mut floor = u64::MAX;
1439		let mut more = false;
1440		while let Some((depth, id)) = queue.pop() {
1441			if newest.contains(&id) {
1442				continue;
1443			}
1444			// A change beyond those looked at: there may be more held here alone.
1445			if newest.len() >= newest_looked_at {
1446				more = true;
1447				break;
1448			}
1449			newest.insert(id);
1450			floor = floor.min(depth);
1451			if let Some(change) = history.change(id)? {
1452				for parent in change.parents() {
1453					if let Some(depth) = history.depth(*parent)? {
1454						queue.push((depth, *parent));
1455					}
1456				}
1457			}
1458		}
1459		// What other disks hold, down to the depth of the oldest of those changes.
1460		let mut elsewhere: BTreeSet<ChangeId> = BTreeSet::new();
1461		let mut walk: Vec<ChangeId> = heads.values().flatten().copied().collect();
1462		while let Some(id) = walk.pop() {
1463			let Some(depth) = history.depth(id)? else {
1464				continue;
1465			};
1466			if depth < floor || !elsewhere.insert(id) {
1467				continue;
1468			}
1469			if let Some(change) = history.change(id)? {
1470				walk.extend(change.parents().iter().copied());
1471			}
1472		}
1473		Ok(ChangeCopies {
1474			needs,
1475			disks: holding.len(),
1476			away,
1477			archived,
1478			here_alone: newest.difference(&elsewhere).count(),
1479			here_alone_more: more,
1480		})
1481	}
1482}
1483
1484#[cfg(test)]
1485mod tests {
1486	use nibkeep_testkit::TestRng;
1487
1488	use super::*;
1489
1490	#[test]
1491	fn changes_held_here_alone_beyond_those_looked_at_say_there_may_be_more() {
1492		let mut rng = TestRng::new("changes beyond");
1493		let directory = nibkeep_testkit::empty_directory(
1494			std::env::temp_dir(),
1495			&format!("nibkeep-accounts-beyond-{}", std::process::id()),
1496		);
1497		let mut library = Library::create(
1498			&directory,
1499			&crate::NewLibrary::new("Ada", "laptop", "nib"),
1500			&nibkeep_keys::NewProtection::Passphrase(
1501				"correct horse",
1502				nibkeep_crypto::PassphraseParams::new(64, 1, 1).expect("valid"),
1503			),
1504			1_760_000_000_000,
1505			&mut rng,
1506		)
1507		.expect("creates");
1508		let space = library.personal_space();
1509		for minute in 1..=12 {
1510			let name = (
1511				nibkeep_model::fields::NAME,
1512				Value::Name(nibkeep_model::Name::new(format!("book {minute}"))),
1513			);
1514			library
1515				.create_entity(
1516					space,
1517					&[],
1518					vec![name],
1519					1_760_000_000_000 + minute * 60_000,
1520					&mut rng,
1521				)
1522				.expect("adds");
1523		}
1524		let copies = library
1525			.copies_by_disk(space, 1_760_000_000_000 + 13 * 60_000)
1526			.expect("counts");
1527		let all = library
1528			.change_copies_among(space, (&copies, crate::Needs::CRITICAL), 1_000)
1529			.expect("counts");
1530		assert!(all.here_alone > 12 && !all.here_alone_more, "{all:?}");
1531		let some = library
1532			.change_copies_among(space, (&copies, crate::Needs::CRITICAL), 5)
1533			.expect("counts");
1534		assert_eq!((some.here_alone, some.here_alone_more), (5, true));
1535		let just = library
1536			.change_copies_among(space, (&copies, crate::Needs::CRITICAL), all.here_alone)
1537			.expect("counts");
1538		assert_eq!(
1539			(just.here_alone, just.here_alone_more),
1540			(all.here_alone, false)
1541		);
1542		drop(library);
1543		let _ = std::fs::remove_dir_all(directory);
1544	}
1545}