Milestone 1: sync engine and lunesync CLI

Rust workspace with core (watch, settle, save, sync over a plain Git
remote, keep-both on same-line edits, offline queueing, tidy) and the
lunesync CLI (device, add, run, service, status, checkpoint, tidy,
history). Tests cover byte-exact round trips, keep-both, offline
catch-up and adopting an existing vault.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 23:11:24 +07:00
commit 25b8be5bbd
18 changed files with 3601 additions and 0 deletions

228
core/src/runner.rs Normal file
View File

@@ -0,0 +1,228 @@
//! The background loop: watch → settle → save → sync, for one vault.
use crate::config::VaultConfig;
use crate::remote;
use crate::state::{self, SyncState};
use crate::vault::{SyncReport, Vault};
use anyhow::{Result, bail};
use notify::{EventKind, RecursiveMode, Watcher};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::mpsc;
use std::time::{Duration, Instant};
/// Timing for bursts of edits (S2).
#[derive(Debug, Clone, Copy)]
pub struct Timing {
/// A burst ends after this much quiet...
pub quiet: Duration,
/// ...or at the latest this long after it started.
pub cap: Duration,
/// When a burst is cut at the cap, files changed more recently than this wait for the next one.
pub settle: Duration,
}
impl Default for Timing {
fn default() -> Self {
Timing { quiet: Duration::from_secs(5), cap: Duration::from_secs(60), settle: Duration::from_secs(2) }
}
}
/// Tracks the current burst of edits.
#[derive(Debug, Default)]
pub struct Burst {
started: Option<Instant>,
last: Option<Instant>,
touched: HashMap<String, Instant>,
}
impl Burst {
pub fn touch(&mut self, path: String, now: Instant) {
self.started.get_or_insert(now);
self.last = Some(now);
self.touched.insert(path, now);
}
pub fn is_idle(&self) -> bool {
self.started.is_none()
}
pub fn due(&self, now: Instant, t: &Timing) -> bool {
match (self.started, self.last) {
(Some(s), Some(l)) => now - l >= t.quiet || now - s >= t.cap,
_ => false,
}
}
/// Ends the burst. Returns files still changing, which must not be saved yet; they start the next burst.
pub fn take(&mut self, now: Instant, t: &Timing) -> HashSet<String> {
let unsettled: HashMap<String, Instant> =
self.touched.drain().filter(|(_, at)| now - *at < t.settle).collect();
let skip = unsettled.keys().cloned().collect();
*self = Burst::default();
if !unsettled.is_empty() {
self.started = Some(now);
self.last = unsettled.values().max().copied();
self.touched = unsettled;
}
skip
}
}
pub type Log<'a> = &'a (dyn Fn(&str, &str) + Sync);
/// Runs forever for one vault. `log(vault, message)` prints progress.
pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log: Log) -> Result<()> {
let vault = Vault::open(cfg, label)?;
let Some(_running) = state::try_run_lock(&vault.git_dir)? else {
bail!("{} is already being synced by another lunesync run", cfg.name);
};
let (tx, rx) = mpsc::channel();
let mut watcher = notify::recommended_watcher(move |ev| {
let _ = tx.send(ev);
})?;
watcher.watch(&vault.root, RecursiveMode::Recursive)?;
let say = |m: &str| log(&vault.name, m);
say(&format!("watching {} as {}", vault.root.display(), label));
let mut burst = Burst::default();
let mut rescan_at = Instant::now(); // pick up anything changed while we weren't running
let mut sync_at = Instant::now();
let mut backoff = poll;
let mut was_waiting = false;
loop {
let first = rx.recv_timeout(Duration::from_millis(250));
for ev in first.into_iter().chain(rx.try_iter()) {
match ev {
Ok(ev) if !matches!(ev.kind, EventKind::Access(_)) => {
for p in ev.paths {
if let Some(rel) = relevant(&vault, &p) {
burst.touch(rel, Instant::now());
}
}
}
Ok(_) => {}
Err(e) => say(&format!("file watcher hiccup: {e}")),
}
}
let now = Instant::now();
let rescan = now >= rescan_at && burst.is_idle();
if rescan || burst.due(now, &timing) {
let skip = burst.take(now, &timing);
rescan_at = now + Duration::from_secs(60);
let _op = state::op_lock(&vault.git_dir)?;
match vault.save_changes(None, &skip) {
Ok(Some(saved)) => {
say(&format!("saved: {}", saved.message));
sync_at = now;
}
Ok(None) => {}
Err(e) => say(&format!("couldn't save changes: {e:#}")),
}
}
if Instant::now() >= sync_at {
let _op = state::op_lock(&vault.git_dir)?;
let result = vault.sync();
let mut st = SyncState::load(&vault.git_dir);
st.last_attempt = Some(chrono::Utc::now().timestamp());
match result {
Ok(report) => {
st.last_error = None;
if !report.waiting_for_local_edits {
st.last_synced = st.last_attempt;
}
if report.waiting_for_local_edits && !was_waiting {
say("new changes are waiting until your current edits settle");
}
was_waiting = report.waiting_for_local_edits;
print_report(&report, &say);
backoff = poll;
sync_at = Instant::now() + poll;
}
Err(e) => {
let msg = remote::describe_error(&e);
if st.last_error.as_deref() != Some(msg.as_str()) {
say(&format!("{msg} — will keep trying"));
}
st.last_error = Some(msg);
backoff = (backoff * 2).min(Duration::from_secs(60));
sync_at = Instant::now() + backoff;
}
}
if let Err(e) = st.save(&vault.git_dir) {
say(&format!("couldn't record sync status: {e:#}"));
}
}
}
}
/// Vault-relative path for a watcher event, or None for our own files and ignored ones.
fn relevant(vault: &Vault, p: &Path) -> Option<String> {
let rel = p.strip_prefix(&vault.root).ok()?;
if rel.as_os_str().is_empty() || rel.starts_with(".git") {
return None;
}
if vault.is_ignored(rel) {
return None;
}
Some(crate::names::slash_path(rel))
}
fn print_report(r: &SyncReport, say: &dyn Fn(&str)) {
if !r.received.is_empty() {
let from: Vec<&str> = r.from.iter().map(String::as_str).collect();
let who = if from.is_empty() { String::new() } else { format!(" from {}", from.join(", ")) };
say(&format!("received {}{who}", count_notes(&r.received)));
}
for (note, copy) in &r.kept_both {
say(&format!("{note} was changed in two places — kept both, yours is in \"{copy}\""));
}
for (old, new) in &r.case_renamed {
say(&format!("{old} clashed with another name differing only by case — renamed to {new}"));
}
if r.shared > 0 {
say(&format!("shared {} change{}", r.shared, if r.shared == 1 { "" } else { "s" }));
}
}
fn count_notes(files: &[String]) -> String {
match files {
[one] => one.clone(),
many => format!("{} notes", many.len()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn burst_ends_after_quiet_or_cap_and_holds_back_unsettled_files() {
let t = Timing::default();
let t0 = Instant::now();
let s = Duration::from_secs;
let mut b = Burst::default();
assert!(!b.due(t0, &t));
b.touch("a.md".into(), t0);
b.touch("b.md".into(), t0 + s(3));
assert!(!b.due(t0 + s(7), &t));
assert!(b.due(t0 + s(8), &t));
assert!(b.take(t0 + s(8), &t).is_empty());
assert!(!b.due(t0 + s(100), &t));
// A file written every second never goes quiet: the cap ends the burst without it.
let mut b = Burst::default();
b.touch("done.md".into(), t0);
for i in 0..=60 {
b.touch("log.md".into(), t0 + s(i));
}
assert!(b.due(t0 + s(60), &t));
let skip = b.take(t0 + s(60), &t);
assert_eq!(skip, HashSet::from(["log.md".to_string()]));
assert!(b.due(t0 + s(65), &t), "the still-changing file starts the next burst");
}
}