garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /sync/src/lib.rs

raw

//! Keeping the vault's files in step between two of a person's devices,
//! and backing them up to a disk (`backup`), as pure state machines like
//! the network stack: messages in ([`Sync::receive`]), messages out
//! ([`Sync::output`]), the files read and written through [`Files`]. The
//! sync service (`programs/src/bin/sync.rs`) carries the messages over a
//! p2p stream; `docs/backup-and-sync.md` has the design.
//!
//! A sync between two devices:
//! 1. Both send their **manifest**: every file's path, size, time of change
//!    and SHA-256 ([`Entry`]; [`Index`] hashes only what changed).
//! 2. The device with the lower key **decides**: from its own version, the
//!    other's and the **base** (what the two last agreed on, which only
//!    the deciding device keeps), it [`plan`]s for each path.
//! 3. It takes, sends and removes files, merges logs both devices added
//!    to, and keeps both versions of a file both changed otherwise.
//! 4. When the other device has written everything, the new base is what
//!    both now hold ([`Outcome::base`]). A sync cut off keeps the old one.

#![no_std]

extern crate alloc;

pub mod backup;
mod wire;

#[cfg(test)]
mod tests;

use alloc::collections::{BTreeMap, VecDeque};
use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_crypto::sha2::Sha256;

pub type Hash = [u8; 32];

/// The largest file kept in step: a file is held whole in memory while it
/// comes.
pub const MAX_FILE: u64 = 16 << 20;
/// The most bytes of a file in one message: with its header, under a
/// channel message's 4096.
pub const PIECE: usize = 3072;
/// The most bytes sent and not yet acknowledged.
const WINDOW: u64 = 256 << 10;
/// The most files asked for at once.
const ASKED: usize = 4;
/// The longest name a file system entry has (`pfs`).
const NAME_MAX: usize = 58;

/// What is kept in step: every path in the vault but what belongs to one
/// device. Paths are the vault's (`/apps/notes/x`, no `data:`).
pub fn synced(path: &str) -> bool {
    !(path == "/p2p/identity"
        || path == "/bt/bonds"
        || path == "/bt/identity"
        || path.starts_with("/sync/")
        || path.starts_with("/display/"))
}

/// A file as one device has it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Entry {
    pub path: String,
    pub size: u64,
    /// Seconds since 1970 (0 without a clock): which of two versions is
    /// newer, nothing more.
    pub modified: u64,
    pub hash: Hash,
}

/// A file as two devices last agreed on it: a line of the base.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Agreed {
    pub path: String,
    pub size: u64,
    pub hash: Hash,
}

pub fn hash(data: &[u8]) -> Hash {
    Sha256::digest(data)
}

/// What the sync reads and writes: the vault, its paths without `data:`.
pub trait Files {
    fn read(&mut self, path: &str) -> Option<Vec<u8>>;
    /// Writes the whole file, making its folders: false when it could not.
    fn write(&mut self, path: &str, data: &[u8]) -> bool;
    fn remove(&mut self, path: &str) -> bool;
}

/// What hashing found, kept between scans: a file whose size and time of
/// change are the same is not read again. A file changed in the second
/// the scan runs is read every time: a second write in that second leaves
/// both the same.
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct Index(pub Vec<Entry>);

impl Index {
    /// The manifest of the files `stats` lists (path, size, time of
    /// change), at `now` (seconds), reading what changed through `read`.
    /// Files not [`synced`], above [`MAX_FILE`], or gone when read are left out.
    pub fn refresh(
        &mut self,
        stats: &[(String, u64, u64)],
        now: u64,
        read: &mut dyn FnMut(&str) -> Option<Vec<u8>>,
    ) -> Vec<Entry> {
        let known: BTreeMap<&str, &Entry> = self.0.iter().map(|e| (e.path.as_str(), e)).collect();
        let mut out = Vec::new();
        for (path, size, modified) in stats {
            if !synced(path) || *size > MAX_FILE {
                continue;
            }
            match known.get(path.as_str()) {
                Some(e) if e.size == *size && e.modified == *modified && *modified < now => {
                    out.push((*e).clone())
                }
                _ => {
                    let Some(data) = read(path) else { continue };
                    out.push(Entry {
                        path: path.clone(),
                        size: data.len() as u64,
                        modified: *modified,
                        hash: hash(&data),
                    });
                }
            }
        }
        out.sort_by(|a, b| a.path.cmp(&b.path));
        self.0 = out.clone();
        out
    }

    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        for e in &self.0 {
            wire::put_entry(&mut out, e);
        }
        out
    }

    pub fn from_bytes(b: &[u8]) -> Index {
        let mut r = wire::Reader(b);
        let mut all = Vec::new();
        while let Some(e) = r.entry() {
            all.push(e);
        }
        Index(all)
    }
}

/// A base as it is kept on disk.
pub fn base_to_bytes(base: &[Agreed]) -> Vec<u8> {
    let mut out = Vec::new();
    for a in base {
        wire::put_agreed(&mut out, a);
    }
    out
}

pub fn base_from_bytes(b: &[u8]) -> Vec<Agreed> {
    let mut r = wire::Reader(b);
    let mut all = Vec::new();
    while let Some(a) = r.agreed() {
        all.push(a);
    }
    all
}

/// What the deciding device does about one path.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Step {
    /// The other's version replaces this one's (or is new here).
    Take(String),
    /// This one's goes there.
    Send(String),
    RemoveHere(String),
    RemoveThere(String),
    /// Both changed it: the other's is fetched, then merged or kept beside.
    Both(String),
}

/// For each path, from this device's version, the other's and the base:
/// `docs/backup-and-sync.md` has the table. Paths both hold alike need no
/// step.
pub fn plan(local: &[Entry], remote: &[Entry], base: &[Agreed]) -> Vec<Step> {
    let l: BTreeMap<&str, &Hash> = local.iter().map(|e| (e.path.as_str(), &e.hash)).collect();
    let r: BTreeMap<&str, &Hash> = remote.iter().map(|e| (e.path.as_str(), &e.hash)).collect();
    let b: BTreeMap<&str, &Hash> = base.iter().map(|a| (a.path.as_str(), &a.hash)).collect();
    let mut paths: Vec<&str> = l.keys().chain(r.keys()).copied().collect();
    paths.sort_unstable();
    paths.dedup();
    let mut steps = Vec::new();
    for p in paths {
        let (lh, rh, bh) = (l.get(p), r.get(p), b.get(p));
        let path = String::from(p);
        let step = match (lh, rh) {
            (Some(x), Some(y)) if x == y => continue,
            (Some(x), Some(y)) => match bh {
                Some(z) if z == x => Step::Take(path),
                Some(z) if z == y => Step::Send(path),
                _ => Step::Both(path),
            },
            // Gone here: removed here since the base, or new there.
            (None, Some(y)) => match bh {
                Some(z) if z == y => Step::RemoveThere(path),
                _ => Step::Take(path),
            },
            (Some(x), None) => match bh {
                Some(z) if z == x => Step::RemoveHere(path),
                _ => Step::Send(path),
            },
            (None, None) => continue,
        };
        steps.push(step);
    }
    steps
}

/// Two versions of a log that both grew from the base: the base, what
/// `first` added, then what `second` added. None when either does not
/// start with the base.
pub fn merge(base: &Agreed, first: &[u8], second: &[u8]) -> Option<Vec<u8>> {
    let n = usize::try_from(base.size).ok()?;
    if n == 0 || first.len() < n || second.len() < n {
        return None;
    }
    if hash(&first[..n]) != base.hash || first[..n] != second[..n] {
        return None;
    }
    let mut out = first.to_vec();
    out.extend_from_slice(&second[n..]);
    Some(out)
}

/// Where the version of `path` that lost its name goes: beside it, as
/// `name (from <device>).ext`, cut to fit a file system name.
pub fn beside(path: &str, device: &str) -> String {
    let (dir, name) = path.rsplit_once('/').unwrap_or(("", path));
    let (stem, ext) = match name.rsplit_once('.') {
        Some((s, e)) if !s.is_empty() => (s, alloc::format!(".{e}")),
        _ => (name, String::new()),
    };
    let device: String = device.chars().filter(|c| *c != '/').take(16).collect();
    let tail = alloc::format!(" (from {device}){ext}");
    let mut stem = String::from(stem);
    while !stem.is_empty() && stem.len() + tail.len() > NAME_MAX {
        stem.pop();
    }
    alloc::format!("{dir}/{stem}{tail}")
}

/// How a sync went.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Outcome {
    /// The new base, on the deciding device: keep it for the next sync.
    pub base: Option<Vec<Agreed>>,
    /// Paths written or removed on this device.
    pub changed: Vec<String>,
    /// Files copied either way.
    pub copied: usize,
    /// Logs merged, and files kept twice because both devices changed them.
    pub merged: usize,
    pub conflicts: usize,
    /// Files the other device, or this one, could not write.
    pub failed: usize,
}

#[derive(Debug, PartialEq, Eq)]
enum State {
    /// Sending this device's manifest and waiting for the other's.
    Lists,
    /// The deciding device working through its steps; the other answering.
    Steps,
    /// The deciding device has said it is done and waits for the answer.
    Ending,
    Done,
}

/// A file coming in, its pieces until it is whole.
struct Incoming {
    path: String,
    size: u64,
    hash: Hash,
    data: Vec<u8>,
    /// None: it is gone there.
    missing: bool,
}

/// One sync with one device, on one side.
pub struct Sync {
    decides: bool,
    me: String,
    other: String,
    state: State,
    local: Vec<Entry>,
    base: Vec<Agreed>,
    remote: Vec<Entry>,
    /// This device's manifest, the messages that carry it, still to send.
    out: VecDeque<Vec<u8>>,
    steps: VecDeque<Step>,
    /// Paths asked for with GET, in the order asked, and whether both
    /// devices changed it.
    asked: VecDeque<(String, bool)>,
    incoming: Option<Incoming>,
    /// Sent with PUT and not yet acknowledged: path, hash, size.
    unacked: VecDeque<Agreed>,
    unacked_bytes: u64,
    agreed: BTreeMap<String, Agreed>,
    outcome: Outcome,
    /// The paths of the other device's last manifest message are in.
    listed: bool,
}

impl Sync {
    /// A sync of `local` (this device's manifest), named `name`, with
    /// another device; `decides` on the device with the lower key, which
    /// alone keeps the `base`.
    pub fn new(decides: bool, name: &str, local: Vec<Entry>, base: Vec<Agreed>) -> Sync {
        let mut out = VecDeque::new();
        out.push_back(wire::hello(name));
        for page in wire::pages(
            wire::LIST,
            local.iter().map(|e| {
                let mut b = Vec::new();
                wire::put_entry(&mut b, e);
                b
            }),
        ) {
            out.push_back(page);
        }
        out.push_back(alloc::vec![wire::LIST_END]);
        Sync {
            decides,
            me: name.into(),
            other: String::new(),
            state: State::Lists,
            local,
            base,
            remote: Vec::new(),
            out,
            steps: VecDeque::new(),
            asked: VecDeque::new(),
            incoming: None,
            unacked: VecDeque::new(),
            unacked_bytes: 0,
            agreed: BTreeMap::new(),
            outcome: Outcome::default(),
            listed: false,
        }
    }

    /// The other device's name, once it said it.
    pub fn other(&self) -> &str {
        &self.other
    }

    /// How it went, once it is over; None while it runs.
    pub fn outcome(&self) -> Option<&Outcome> {
        (self.state == State::Done).then_some(&self.outcome)
    }

    /// The next message for the other device, if one is due.
    pub fn output(&mut self, files: &mut dyn Files) -> Option<Vec<u8>> {
        if let Some(m) = self.out.pop_front() {
            return Some(m);
        }
        if !self.decides || self.state != State::Steps {
            return None;
        }
        while let Some(step) = self.steps.front() {
            match step {
                Step::Send(_) if self.unacked_bytes >= WINDOW => return None,
                // What is asked for comes all at once: a few files, and
                // their bytes within the window (one file, whatever its size).
                Step::Take(_) | Step::Both(_)
                    if !self.asked.is_empty()
                        && (self.asked.len() >= ASKED || self.asked_bytes() >= WINDOW) =>
                {
                    return None;
                }
                _ => {}
            }
            let step = self.steps.pop_front().unwrap();
            let both = matches!(step, Step::Both(_));
            match step {
                Step::Send(path) => {
                    let Some(data) = files.read(&path) else {
                        // Gone since the manifest: the next sync sees it.
                        self.keep_base(&path);
                        continue;
                    };
                    self.put(&path, &data);
                }
                Step::Take(path) | Step::Both(path) => {
                    self.out.push_back(wire::path_message(wire::GET, &path));
                    self.asked.push_back((path, both));
                }
                Step::RemoveHere(path) => {
                    if files.remove(&path) {
                        self.outcome.changed.push(path);
                    } else {
                        self.outcome.failed += 1;
                        self.keep_base(&path);
                    }
                }
                Step::RemoveThere(path) => {
                    self.out.push_back(wire::path_message(wire::REMOVE, &path));
                }
            }
            if let Some(m) = self.out.pop_front() {
                return Some(m);
            }
        }
        if self.asked.is_empty() && self.unacked.is_empty() && self.incoming.is_none() {
            self.state = State::Ending;
            return Some(alloc::vec![wire::DONE]);
        }
        None
    }

    /// A message from the other device.
    pub fn receive(&mut self, message: &[u8], files: &mut dyn Files) {
        let Some((&kind, body)) = message.split_first() else {
            return;
        };
        match kind {
            wire::HELLO => self.other = String::from_utf8_lossy(body).into_owned(),
            wire::LIST => {
                let mut r = wire::Reader(body);
                while let Some(e) = r.entry() {
                    self.remote.push(e);
                }
            }
            wire::LIST_END => {
                self.listed = true;
                self.state = State::Steps;
                if self.decides {
                    self.decide();
                }
            }
            wire::GET if !self.decides => {
                let path = String::from_utf8_lossy(body).into_owned();
                match files.read(&path) {
                    Some(data) => {
                        self.out
                            .push_back(wire::file(wire::FILE, &path, data.len() as u64, &hash(&data)));
                        for piece in data.chunks(PIECE) {
                            self.out.push_back([&[wire::PIECE_KIND][..], piece].concat());
                        }
                    }
                    None => self
                        .out
                        .push_back(wire::file(wire::FILE, &path, u64::MAX, &[0; 32])),
                }
            }
            wire::PUT | wire::FILE => {
                let mut r = wire::Reader(body);
                let (Some(path), Some(size), Some(hash)) = (r.path(), r.u64(), r.hash()) else {
                    return;
                };
                let missing = size == u64::MAX;
                self.incoming = Some(Incoming {
                    path,
                    size: if missing { 0 } else { size },
                    hash,
                    data: Vec::new(),
                    missing,
                });
                self.incoming_progress(kind == wire::PUT, files);
            }
            wire::PIECE_KIND => {
                let Some(i) = self.incoming.as_mut() else { return };
                i.data.extend_from_slice(body);
                let from_put = !self.decides;
                self.incoming_progress(from_put, files);
            }
            wire::REMOVE if !self.decides => {
                let path = String::from_utf8_lossy(body).into_owned();
                if files.remove(&path) {
                    self.outcome.changed.push(path);
                }
            }
            wire::ACK if self.decides => {
                let ok = body.first() == Some(&1);
                if let Some(a) = self.unacked.pop_front() {
                    self.unacked_bytes -= a.size.min(self.unacked_bytes);
                    if ok {
                        self.outcome.copied += 1;
                        self.agreed.insert(a.path.clone(), a);
                    } else {
                        self.outcome.failed += 1;
                        self.keep_base(&a.path);
                    }
                }
            }
            wire::DONE => {
                if self.decides {
                    if self.state == State::Ending {
                        self.outcome.base = Some(self.agreed.values().cloned().collect());
                        self.state = State::Done;
                    }
                } else {
                    self.out.push_back(alloc::vec![wire::DONE]);
                    self.state = State::Done;
                }
            }
            _ => {}
        }
    }

    /// The size of what is asked for and not yet in, as the other's
    /// manifest gave it.
    fn asked_bytes(&self) -> u64 {
        self.asked
            .iter()
            .filter_map(|(p, _)| self.remote.iter().find(|e| e.path == *p))
            .map(|e| e.size)
            .sum()
    }

    /// Paths both hold alike are agreed at once; the rest become steps.
    fn decide(&mut self) {
        let remote: BTreeMap<&str, &Hash> = self.remote.iter().map(|e| (e.path.as_str(), &e.hash)).collect();
        for e in &self.local {
            if remote.get(e.path.as_str()) == Some(&&e.hash) {
                self.agreed.insert(
                    e.path.clone(),
                    Agreed {
                        path: e.path.clone(),
                        size: e.size,
                        hash: e.hash,
                    },
                );
            }
        }
        self.steps = plan(&self.local, &self.remote, &self.base).into();
    }

    /// Keeps what the base said of `path`: a step that could not be done
    /// leaves the two as they were.
    fn keep_base(&mut self, path: &str) {
        if let Some(a) = self.base.iter().find(|a| a.path == path) {
            self.agreed.insert(a.path.clone(), a.clone());
        }
    }

    fn put(&mut self, path: &str, data: &[u8]) {
        let h = hash(data);
        self.out
            .push_back(wire::file(wire::PUT, path, data.len() as u64, &h));
        for piece in data.chunks(PIECE) {
            self.out.push_back([&[wire::PIECE_KIND][..], piece].concat());
        }
        self.unacked_bytes += data.len() as u64;
        self.unacked.push_back(Agreed {
            path: path.into(),
            size: data.len() as u64,
            hash: h,
        });
    }

    /// A file coming in: once whole, written (sent to this side with PUT)
    /// or decided on (fetched with GET).
    fn incoming_progress(&mut self, put: bool, files: &mut dyn Files) {
        let Some(i) = &self.incoming else { return };
        if (i.data.len() as u64) < i.size {
            return;
        }
        let i = self.incoming.take().unwrap();
        let whole = !i.missing && i.data.len() as u64 == i.size && hash(&i.data) == i.hash;
        if put {
            let ok = whole && files.write(&i.path, &i.data);
            if ok {
                self.outcome.changed.push(i.path.clone());
                self.outcome.copied += 1;
            } else {
                self.outcome.failed += 1;
            }
            self.out.push_back(alloc::vec![wire::ACK, u8::from(ok)]);
            return;
        }
        // An answer to a GET, on the deciding device.
        let Some(at) = self.asked.iter().position(|(p, _)| *p == i.path) else {
            return;
        };
        let (_, both) = self.asked.remove(at).unwrap();
        if i.missing {
            // Gone there since its manifest: the next sync sees it.
            self.keep_base(&i.path);
            return;
        }
        if !whole {
            self.outcome.failed += 1;
            self.keep_base(&i.path);
            return;
        }
        let mine = self.local.iter().find(|e| e.path == i.path).cloned();
        let here = files.read(&i.path);
        if here.as_deref().map(hash) != mine.as_ref().map(|e| e.hash) {
            // Changed here while this ran: the next sync decides.
            self.keep_base(&i.path);
            return;
        }
        let (Some(mine), Some(here), true) = (mine, here, both) else {
            self.take(&i.path, &i.data, files);
            return;
        };
        // Both changed it: a log both added to is merged.
        let base = self.base.iter().find(|a| a.path == i.path).cloned();
        if let Some(merged) = base.and_then(|b| merge(&b, &here, &i.data)) {
            self.outcome.merged += 1;
            if files.write(&i.path, &merged) {
                self.outcome.changed.push(i.path.clone());
                self.put(&i.path, &merged);
            } else {
                self.outcome.failed += 1;
                self.keep_base(&i.path);
            }
            return;
        }
        // Otherwise both are kept: the newer under the name, the other
        // beside it, named for the device it came from.
        self.outcome.conflicts += 1;
        let theirs_newer = self
            .remote
            .iter()
            .any(|e| e.path == i.path && e.modified > mine.modified);
        let (aside, loses) = if theirs_newer {
            self.take(&i.path, &i.data, files);
            (beside(&i.path, &self.me), here)
        } else {
            self.put(&i.path, &here);
            (beside(&i.path, &self.other), i.data)
        };
        if files.write(&aside, &loses) {
            self.outcome.changed.push(aside.clone());
            self.put(&aside, &loses);
        } else {
            self.outcome.failed += 1;
        }
    }

    fn take(&mut self, path: &str, data: &[u8], files: &mut dyn Files) {
        if files.write(path, data) {
            self.outcome.changed.push(path.into());
            self.outcome.copied += 1;
            self.agreed.insert(
                path.into(),
                Agreed {
                    path: path.into(),
                    size: data.len() as u64,
                    hash: hash(data),
                },
            );
        } else {
            self.outcome.failed += 1;
            self.keep_base(path);
        }
    }
}