griz-store 0.6.4

Durable journal, locks, and recovery for griz edits
Documentation
//! Select restore membership and lock paths without retaining full records.

use crate::{Store, StoreError};
use rusqlite::{Connection, OptionalExtension};
use serde::Deserialize;
use std::{
    collections::BTreeSet,
    path::{Path, PathBuf},
};

pub(crate) struct RestoreSelection {
    pub(crate) ids: Vec<String>,
    pub(crate) paths: Vec<PathBuf>,
}

#[derive(Deserialize)]
struct LockRecord {
    id: String,
    files: Vec<LockFile>,
}

#[derive(Deserialize)]
struct LockFile {
    path: PathBuf,
}

impl Store {
    /// One store holds every repository's history, so the span is always
    /// narrowed to `root` first; `paths` narrows it further within that root.
    pub(crate) fn select_restore(
        &self,
        since: &str,
        root: &Path,
        paths: &[PathBuf],
    ) -> Result<RestoreSelection, StoreError> {
        self.with(|conn| select(conn, since, root, paths))
    }
}

fn select(
    conn: &Connection,
    since: &str,
    root: &Path,
    paths: &[PathBuf],
) -> Result<RestoreSelection, StoreError> {
    let sequence: i64 = conn
        .query_row(
            "SELECT sequence FROM operations WHERE id = ?1",
            [since],
            |row| row.get(0),
        )
        .optional()?
        .ok_or_else(|| StoreError::NotFound(format!("operation {since}")))?;
    let mut statement = conn.prepare(
        "SELECT body FROM operations WHERE sequence >= ?1 AND state = 'applied' ORDER BY sequence",
    )?;
    let mut rows = statement.query([sequence])?;
    let mut ids = Vec::new();
    let mut locked = BTreeSet::new();
    while let Some(row) = rows.next()? {
        let body: String = row.get(0)?;
        let record: LockRecord = serde_json::from_str(&body)?;
        let id = record.id;
        let touching = record
            .files
            .into_iter()
            .map(|file| file.path)
            .filter(|path| path.starts_with(root))
            .filter(|path| paths.is_empty() || paths.contains(path));
        let mut touched = false;
        for path in touching {
            touched = true;
            locked.insert(path);
        }
        if touched {
            ids.push(id);
        }
    }
    Ok(RestoreSelection {
        ids,
        paths: locked.into_iter().collect(),
    })
}