1use 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
22const DISK_CONTEXT: &str = "nibkeep 2026-11 disk";
24
25const NEWEST_LOOKED_AT: usize = 10_000;
27
28const REFRESHED_FOR: u64 = 60_000;
33
34const BACKUPS_PER_REPLICA: usize = 8;
36
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39pub struct DeviceMarks {
40 pub role: DeviceRole,
43 pub away: bool,
45 pub keeps: Option<u64>,
49 pub waits: Option<u64>,
52}
53
54#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct Disk {
58 pub id: Hash,
60 pub here: bool,
62 pub replicas: Vec<DiskReplica>,
64 pub archive: bool,
66 pub away: bool,
68 pub issued: Option<u64>,
71 pub damaged: u64,
74 pub unrepaired: u64,
76 pub backups: Vec<DiskBackup>,
78}
79
80#[derive(Clone, Debug, PartialEq, Eq)]
84pub struct DiskBackup {
85 pub backup: EntityId,
87 pub name: Option<String>,
89 pub update: u64,
91}
92
93#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct DiskReplica {
96 pub replica: Option<EntityId>,
98 pub name: Option<String>,
100 pub device: Option<String>,
102 pub member: Option<String>,
104 pub this: bool,
106}
107
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub enum CopyHeld {
111 Sealed {
114 checked: Option<u64>,
116 },
117 InPlace {
121 checked: Option<u64>,
123 },
124}
125
126#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct FileCopy {
129 pub disk: Disk,
131 pub held: CopyHeld,
133 pub counts: bool,
138}
139
140#[derive(Clone, Debug, PartialEq, Eq)]
143pub struct ChangeCopies {
144 pub needs: crate::Needs,
146 pub disks: usize,
148 pub away: usize,
150 pub archived: usize,
152 pub here_alone: usize,
154 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
172pub(crate) type Checked = BTreeMap<Hash, u64>;
175
176pub(crate) struct Listed {
178 pub(crate) disk: Hash,
180 pub(crate) sealed: Checked,
182 pub(crate) plain: Checked,
184}
185
186type PagesAbout = (Option<(BackupHead, u64)>, Vec<(Hash, u64)>);
189
190pub(crate) struct BackupAccount {
192 pub(crate) head: BackupHead,
194 pub(crate) issued: u64,
196 pub(crate) blobs: Vec<(Hash, u64)>,
198}
199
200#[derive(Default)]
202struct Account {
203 head: Option<(Head, u64)>,
204 blobs: Vec<(Hash, u64)>,
205 copies: Vec<(EntityId, Hash, u64)>,
206}
207
208pub(crate) struct Copies {
211 pub(crate) disks: Vec<Disk>,
213 by_sealed: BTreeMap<Hash, Vec<(usize, u64)>>,
216 by_copy: BTreeMap<(EntityId, Hash), Vec<(usize, u64)>>,
219 heads: Vec<(usize, Vec<ChangeId>)>,
221 since: u64,
223}
224
225impl Copies {
226 pub(crate) const OWN: usize = 0;
228
229 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 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 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 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
298pub(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
311fn 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 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 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 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 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 if device == self.info.device {
434 self.refresh_wait(wall_millis)?;
435 }
436 Ok(())
437 }
438
439 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 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 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 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 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 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 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 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 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 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 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 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 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 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 fn add_backup_copies(
858 &self,
859 space: SpaceId,
860 copies: &mut Copies,
861 by_id: &mut BTreeMap<Hash, usize>,
862 ) -> Result<(), NodeError> {
863 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 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 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 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 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 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 fn other_accounts(&self, space: SpaceId) -> Result<BTreeMap<[u8; 32], Account>, NodeError> {
1070 self.other_accounts_where(space, |_, _| true)
1071 }
1072
1073 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}