second-brain-sync 0.13.4

Bidirectional sync for second-brain: SSH transport, JSONL change log, conflict resolution
Documentation
use std::sync::Mutex;

use anyhow::{Context, Result};
use second_brain_core::keys::{DeviceRecord, valid_host_key, valid_login};

use super::Keyring;
use crate::pairing::SshServer;

/// Held from reading this device's row to storing its next version, so two
/// writers never sign the same version and one of them fails.
static OWN_ROW_WRITE: Mutex<()> = Mutex::new(());

impl Keyring<'_> {
    /// Signs the next version of this device's row when `edit` changes it.
    /// False when `edit` changed nothing.
    pub(super) fn update_own_row(&self, edit: impl FnOnce(&mut DeviceRecord)) -> Result<bool> {
        let _writing = OWN_ROW_WRITE
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let own = self.own();
        let current = self
            .store
            .device_record(own)?
            .context("this device has no signed row")?
            .current
            .record;
        let mut record = current.clone();
        edit(&mut record);
        if record == current {
            return Ok(false);
        }
        record.version = current.version + 1;
        self.store
            .update_device_record(&record.sign(own, self.device.signing_key()))
    }

    /// Puts this device's sshd into its signed row, so every device of its
    /// identity can pin its host key and dial it, whichever device paired
    /// it. A field `ssh` lacks, or holds in a form unsafe for ssh, keeps its
    /// signed value. False when nothing changed or this device has no row.
    pub fn sign_own_ssh(&self, ssh: &SshServer) -> Result<bool> {
        if self.store.device_record(self.own())?.is_none() {
            return Ok(false);
        }
        self.update_own_row(|record| {
            if let Some(login) = ssh.login.as_ref().filter(|login| valid_login(login)) {
                record.ssh_login = Some(login.clone());
            }
            if ssh.port != 0 {
                record.ssh_port = Some(ssh.port);
            }
            if let Some(host_key) = ssh.row_host_key().filter(|key| valid_host_key(key)) {
                record.ssh_host_key = Some(host_key.to_string());
            }
        })
    }
}