Skip to main content

second_brain_sync/
peers.rs

1use std::fs;
2use std::io;
3use std::path::Path;
4use std::sync::{Mutex, PoisonError};
5
6use anyhow::{Context, Result};
7use chrono::{DateTime, Utc};
8
9pub const PEERS_FILE: &str = "sync-peers";
10pub const SUCCESS_FILE: &str = "sync-succeeded";
11
12/// The lines of `sync-peers`, each read by [`Peer::parse`]; blank lines and
13/// `#` comments are skipped. None when there is no such file.
14pub fn configured_peers(data_dir: &Path) -> io::Result<Option<Vec<String>>> {
15    let text = match fs::read_to_string(data_dir.join(PEERS_FILE)) {
16        Ok(text) => text,
17        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
18        Err(e) => return Err(e),
19    };
20    Ok(Some(
21        text.lines()
22            .map(str::trim)
23            .filter(|line| !line.is_empty() && !line.starts_with('#'))
24            .map(str::to_string)
25            .collect(),
26    ))
27}
28
29/// A `sync-peers` line: the ssh destination, then optionally the path of `sb`
30/// on that peer, for a peer whose non-interactive ssh PATH lacks it.
31#[derive(Debug, Clone, PartialEq, Eq, Hash)]
32pub struct Peer {
33    pub host: String,
34    pub sb: String,
35}
36
37impl Peer {
38    pub fn parse(line: &str) -> Self {
39        let mut fields = line.split_whitespace();
40        Self {
41            host: fields.next().unwrap_or_default().to_string(),
42            sb: fields.next().unwrap_or("sb").to_string(),
43        }
44    }
45}
46
47pub fn configured_peer(data_dir: &Path, host: &str) -> io::Result<Option<Peer>> {
48    Ok(configured_peers(data_dir)?
49        .unwrap_or_default()
50        .iter()
51        .map(|line| Peer::parse(line))
52        .find(|peer| peer.host == host))
53}
54
55/// The staged file is named by pid, so threads of one process take turns.
56static RECORDING: Mutex<()> = Mutex::new(());
57
58/// Call only once a pull and a push have both finished; health counts it as
59/// a sync that succeeded.
60pub fn record_success(data_dir: &Path, at: DateTime<Utc>) -> Result<()> {
61    let _turn = RECORDING.lock().unwrap_or_else(PoisonError::into_inner);
62    fs::create_dir_all(data_dir).with_context(|| format!("creating {}", data_dir.display()))?;
63    let path = data_dir.join(SUCCESS_FILE);
64    let staged = data_dir.join(format!("{SUCCESS_FILE}.{}.tmp", std::process::id()));
65    fs::write(&staged, format!("{}\n", at.to_rfc3339()))
66        .with_context(|| format!("writing {}", staged.display()))?;
67    fs::rename(&staged, &path).with_context(|| format!("replacing {}", path.display()))?;
68    Ok(())
69}
70
71pub fn last_success(data_dir: &Path) -> Result<Option<DateTime<Utc>>> {
72    let path = data_dir.join(SUCCESS_FILE);
73    let text = match fs::read_to_string(&path) {
74        Ok(text) => text,
75        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
76        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
77    };
78    let at = DateTime::parse_from_rfc3339(text.trim())
79        .with_context(|| format!("{} does not hold an RFC 3339 time", path.display()))?;
80    Ok(Some(at.with_timezone(&Utc)))
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    #[test]
88    fn a_missing_peers_file_is_told_apart_from_an_empty_one() {
89        let dir = tempfile::tempdir().unwrap();
90        assert_eq!(configured_peers(dir.path()).unwrap(), None);
91        std::fs::write(dir.path().join(PEERS_FILE), "# none yet\n").unwrap();
92        assert_eq!(configured_peers(dir.path()).unwrap(), Some(Vec::new()));
93    }
94
95    #[test]
96    fn peers_skip_blank_lines_and_comments() {
97        let dir = tempfile::tempdir().unwrap();
98        std::fs::write(
99            dir.path().join(PEERS_FILE),
100            "# laptop\nuser@laptop\n\n   \n  user@desktop.local  \n#user@old\n",
101        )
102        .unwrap();
103        assert_eq!(
104            configured_peers(dir.path()).unwrap(),
105            Some(vec![
106                "user@laptop".to_string(),
107                "user@desktop.local".to_string()
108            ])
109        );
110    }
111
112    #[test]
113    fn the_last_success_is_what_was_last_recorded() {
114        let dir = tempfile::tempdir().unwrap();
115        assert_eq!(last_success(dir.path()).unwrap(), None);
116        let first = Utc::now() - chrono::Duration::hours(30);
117        let second = Utc::now();
118        record_success(dir.path(), first).unwrap();
119        assert_eq!(last_success(dir.path()).unwrap(), Some(first));
120        record_success(dir.path(), second).unwrap();
121        assert_eq!(last_success(dir.path()).unwrap(), Some(second));
122    }
123
124    #[test]
125    fn recording_creates_the_data_dir() {
126        let dir = tempfile::tempdir().unwrap();
127        let data_dir = dir.path().join("fresh");
128        let at = Utc::now();
129        record_success(&data_dir, at).unwrap();
130        assert_eq!(last_success(&data_dir).unwrap(), Some(at));
131    }
132
133    #[test]
134    fn a_peer_line_names_the_host_and_optionally_the_peers_sb() {
135        assert_eq!(
136            Peer::parse("user@laptop"),
137            Peer {
138                host: "user@laptop".to_string(),
139                sb: "sb".to_string()
140            }
141        );
142        assert_eq!(
143            Peer::parse("user@pi.local   /home/user/.cargo/bin/sb"),
144            Peer {
145                host: "user@pi.local".to_string(),
146                sb: "/home/user/.cargo/bin/sb".to_string()
147            }
148        );
149    }
150
151    #[test]
152    fn a_configured_peer_is_found_by_its_host() {
153        let dir = tempfile::tempdir().unwrap();
154        assert_eq!(configured_peer(dir.path(), "user@pi").unwrap(), None);
155        std::fs::write(
156            dir.path().join(PEERS_FILE),
157            "user@laptop\nuser@pi /opt/sb\n",
158        )
159        .unwrap();
160        assert_eq!(
161            configured_peer(dir.path(), "user@pi").unwrap(),
162            Some(Peer::parse("user@pi /opt/sb"))
163        );
164        assert_eq!(configured_peer(dir.path(), "user@desk").unwrap(), None);
165    }
166
167    #[test]
168    fn threads_recording_at_once_all_succeed() {
169        let dir = tempfile::tempdir().unwrap();
170        let handles: Vec<_> = (0..16)
171            .map(|_| {
172                let dir = dir.path().to_path_buf();
173                std::thread::spawn(move || {
174                    for _ in 0..50 {
175                        record_success(&dir, Utc::now()).unwrap();
176                    }
177                })
178            })
179            .collect();
180        for handle in handles {
181            handle.join().unwrap();
182        }
183        assert!(last_success(dir.path()).unwrap().is_some());
184    }
185
186    #[test]
187    fn an_unreadable_success_stamp_is_an_error() {
188        let dir = tempfile::tempdir().unwrap();
189        std::fs::write(dir.path().join(SUCCESS_FILE), "yesterday\n").unwrap();
190        assert!(last_success(dir.path()).is_err());
191    }
192}