second-brain-sync 0.13.3

Bidirectional sync for second-brain: SSH transport, JSONL change log, conflict resolution
Documentation
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;

use anyhow::{Context, Result, anyhow, bail};
use serde::Serialize;

use super::channel::Channel;
use super::code::JoinCode;
use super::{Admission, HostReply, JoinRequest, JoinerAck, KeyHandover, KeyRequest};

const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);

/// A join whose admission `take` stored.
#[derive(Debug)]
pub struct Taken<T> {
    pub taken: T,
    pub admission: Admission,
    /// Why the pairing device was not told the join succeeded, so it may
    /// show the pairing as failed although this device joined.
    pub unacked: Option<String>,
}

/// Dials the pairing device at the first of `addresses` that answers,
/// proves `code`, sends `request` and hands the admission to `take`, whose
/// outcome the pairing device is told. Once `take` stored the admission the
/// join stands, so a failed final ack is reported, not returned as an error.
pub fn join<T>(
    addresses: &[(String, u16)],
    code: &JoinCode,
    request: &JoinRequest,
    take: impl FnOnce(&Admission, &str) -> Result<T>,
) -> Result<Taken<T>> {
    let (mut channel, host) = open(addresses, code, request)?;
    let admission = match channel.recv_json::<HostReply>()? {
        HostReply::Admitted(admission) => *admission,
        HostReply::Refused { reason } => bail!("the pairing device refused this device: {reason}"),
        HostReply::KeysHandedOver(_) => bail!(
            "that device runs `sb pair --restore-keys`, which hands keys to a restore and adds \
             no device; run `sb pair` there to pair"
        ),
    };
    let (taken, unacked) = answer(&mut channel, take(&admission, &host))?;
    Ok(Taken {
        taken,
        admission,
        unacked,
    })
}

/// Dials a device running `sb pair --restore-keys`, proves `code` and hands
/// the epochs it sends to `take`, whose outcome that device is told. It
/// returns what `take` made of them and why the final ack failed, if it did.
pub fn fetch_keys<T>(
    addresses: &[(String, u16)],
    code: &JoinCode,
    request: &KeyRequest,
    take: impl FnOnce(&KeyHandover) -> Result<T>,
) -> Result<(T, Option<String>)> {
    let (mut channel, _) = open(addresses, code, request)?;
    let handover = match channel.recv_json::<HostReply>()? {
        HostReply::KeysHandedOver(handover) => *handover,
        HostReply::Refused { reason } => bail!("the other device refused: {reason}"),
        HostReply::Admitted(_) => {
            let reason = "this device asked for keys to restore a backup, not to pair";
            if let Err(e) = channel.send_json(&JoinerAck::Failed {
                reason: reason.into(),
            }) {
                tracing::warn!("could not tell the other device the restore failed: {e:#}");
            }
            bail!(
                "that device paired this one instead of handing over keys; run `sb pair --restore-keys` there"
            )
        }
    };
    answer(&mut channel, take(&handover))
}

/// Fails unless something listens at one of `addresses`. The connection
/// is closed without proving a code, so it costs the listener no try.
pub fn reachable(addresses: &[(String, u16)]) -> Result<()> {
    dial(addresses).map(drop)
}

fn open(
    addresses: &[(String, u16)],
    code: &JoinCode,
    request: &impl Serialize,
) -> Result<(Channel, String)> {
    let (stream, host) = dial(addresses)?;
    let mut channel = Channel::connect(stream, code)?;
    channel.send_json(request)?;
    Ok((channel, host))
}

/// Tells the other device how `taken` went; once it is Ok it stands, so a
/// failed ack is returned beside it rather than as an error.
fn answer<T>(channel: &mut Channel, taken: Result<T>) -> Result<(T, Option<String>)> {
    match taken {
        Ok(taken) => {
            let unacked = channel
                .send_json(&JoinerAck::Joined)
                .err()
                .map(|e| format!("{e:#}"));
            Ok((taken, unacked))
        }
        Err(e) => {
            let reason = format!("{e:#}");
            if let Err(send) = channel.send_json(&JoinerAck::Failed { reason }) {
                tracing::warn!("could not tell the pairing device the join failed: {send:#}");
            }
            Err(e)
        }
    }
}

fn dial(addresses: &[(String, u16)]) -> Result<(TcpStream, String)> {
    let mut failures = Vec::new();
    for (host, port) in addresses {
        let resolved = match (host.as_str(), *port).to_socket_addrs() {
            Ok(resolved) => resolved,
            Err(e) => {
                failures.push(format!("{host}: {e}"));
                continue;
            }
        };
        for addr in resolved {
            match TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT) {
                Ok(stream) => return Ok((stream, host.clone())),
                Err(e) => failures.push(format!("{addr}: {e}")),
            }
        }
    }
    if addresses.is_empty() {
        return Err(anyhow!("no address to reach the pairing device at"));
    }
    Err(anyhow!(failures.join("; ")))
        .context("no pairing device answered; check `sb pair` is running there and the host")
}