second-brain-sync 0.13.1

Bidirectional sync for second-brain: SSH transport, JSONL change log, conflict resolution
Documentation
use anyhow::Result;
use second_brain_core::keys::{Epoch, PeerView};
use serde::Serialize;

use super::Keyring;
use crate::protocol::HandshakeKeys;

/// This device's standing in its sync identity, as the store shows it.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct IdentityStatus {
    pub identity: Option<String>,
    /// Numbers of the epochs this device holds an envelope for.
    pub epochs: Vec<u32>,
    /// A revocation this device holds reaches it.
    pub removed: bool,
    /// Removed, or a peer that holds this device's row has an epoch it did
    /// not wrap to this device.
    pub possibly_revoked: bool,
    /// Whether any peer's last hello listed this device's row; None until
    /// a hello from a device still in the identity was taken.
    pub row_accepted: Option<bool>,
    pub peers: Vec<PeerStanding>,
    /// Recovery phrases retired under this identity: none of them opens an
    /// epoch minted after its retirement.
    pub retired_recovery: Vec<RetiredPhrase>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RetiredPhrase {
    pub fingerprint: String,
    /// None when only an epoch's cause named it, so no device here could
    /// verify who retired it.
    pub retired_by: Option<String>,
    pub at_micros: Option<i64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PeerStanding {
    pub peer: String,
    pub heard_at_micros: i64,
    pub holds_own_row: bool,
    /// Epochs the peer holds that this device cannot open.
    pub lacking: Vec<u32>,
}

impl Keyring<'_> {
    pub fn status(&self) -> Result<IdentityStatus> {
        let Some(tag) = &self.identity else {
            return Ok(IdentityStatus::default());
        };
        let removed = self.is_removed()?;
        let mut peers = Vec::new();
        for view in self.store.peer_views(tag)? {
            if self.active_row(&view.peer)?.is_none() {
                continue;
            }
            peers.push(PeerStanding {
                peer: view.peer,
                heard_at_micros: view.heard_at_micros,
                holds_own_row: view.holds_own_row,
                lacking: view.lacking.iter().map(|e| e.number).collect(),
            });
        }
        let row_accepted = (!peers.is_empty()).then(|| peers.iter().any(|p| p.holds_own_row));
        let possibly_revoked = removed
            || peers
                .iter()
                .any(|p| p.holds_own_row && !p.lacking.is_empty());
        let mut epochs: Vec<u32> = self.stored_epochs()?.iter().map(|e| e.number).collect();
        epochs.sort_unstable();
        epochs.dedup();
        let retired_recovery = self
            .store
            .retired_under(tag)?
            .into_iter()
            .map(|(fingerprint, signed)| RetiredPhrase {
                retired_by: signed
                    .as_ref()
                    .map(|s| self.device_name(&s.retirement.retirer)),
                at_micros: signed.as_ref().map(|s| s.retirement.created_at_micros),
                fingerprint,
            })
            .collect();
        Ok(IdentityStatus {
            identity: Some(tag.as_str().to_string()),
            epochs,
            removed,
            possibly_revoked,
            row_accepted,
            peers,
            retired_recovery,
        })
    }

    /// Run after a peer's hello was taken, so `lacking` names only the
    /// epochs it held back from this device.
    pub(super) fn record_peer_view(
        &self,
        peer: &str,
        keys: &HandshakeKeys,
        now_micros: i64,
    ) -> Result<()> {
        let Some(tag) = &self.identity else {
            return Ok(());
        };
        if peer == self.own() {
            return Ok(());
        }
        let own_key = self.device.verifying_key();
        let holds_own_row = keys.devices.iter().any(|row| {
            row.record.machine_id == self.own()
                && row.record.identity_tag == tag.as_str()
                && row
                    .record
                    .signing_public_key()
                    .is_ok_and(|key| key == own_key)
        });
        let held = self.stored_epochs()?;
        let lacking = keys
            .epochs
            .iter()
            .filter(|epoch| !held.contains(epoch))
            .copied()
            .collect();
        self.store.record_peer_view(
            tag,
            &PeerView {
                peer: peer.to_string(),
                heard_at_micros: now_micros,
                holds_own_row,
                lacking,
            },
        )
    }

    fn stored_epochs(&self) -> Result<Vec<Epoch>> {
        let recipient = self.device.age_recipient().to_string();
        Ok(self
            .store
            .own_identity_envelopes(&recipient)?
            .map(|(_, envelopes)| envelopes.into_iter().map(|e| e.epoch).collect())
            .unwrap_or_default())
    }
}