zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! The supervised VPN (zc#513/#514): every ~30 s, when this node is meant to
//! be on the mesh, check the tunnel and repair it. Before this the agent only
//! read `vpn::route()`; a tunnel that dropped (a sleep, a Wi-Fi change, a
//! stale handshake) stayed down until someone ran `zc vpn`.
//!
//! The tunnel counts as down when its interface is gone, or when it has peers
//! and the newest handshake is older than [`STALE_AFTER_SECS`]. A repair is
//! `vpn::ensure` with an exponential backoff between attempts (the series of
//! [`plan::restart_backoff`], scaled to the check interval). A `vpn_down`
//! problem is raised on the first failed repair and cleared once the tunnel
//! is healthy again. `ZAKURO_VPN_WATCH=0` turns the watcher off.
//!
//! All host access is behind [`Probe`]: the tests use fakes, never WireGuard.

use crate::agent::plan::restart_backoff;
use std::time::{Duration, Instant};

pub const EVERY: Duration = Duration::from_secs(30);
/// WireGuard re-handshakes about every two minutes under traffic; past this
/// the peer is not answering.
pub const STALE_AFTER_SECS: u64 = 180;
const MAX_WAIT: Duration = Duration::from_secs(15 * 60);

/// What the tunnel looks like right now.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Observation {
    /// The mesh interface (or the sidecar's proxy) is there.
    pub up: bool,
    /// Whether the tunnel lists any peer to have a handshake with.
    pub has_peers: bool,
    /// Seconds since the newest handshake; `None` = never.
    pub handshake_age: Option<u64>,
}

pub trait Probe {
    /// Is this node meant to be on the mesh (sharing is on, and a tunnel was
    /// set up here)? When not, the watcher leaves the tunnel alone.
    fn wanted(&self) -> bool;
    fn observe(&self) -> Observation;
    /// Bring the tunnel up (`vpn::ensure`).
    fn repair(&self) -> Result<(), String>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
    Healthy,
    Down(String),
}

pub fn judge(o: &Observation) -> Verdict {
    if !o.up {
        return Verdict::Down("the mesh interface is not up".into());
    }
    if o.has_peers {
        match o.handshake_age {
            None => return Verdict::Down("no handshake with the mesh yet".into()),
            Some(a) if a > STALE_AFTER_SECS => {
                return Verdict::Down(format!("the last handshake was {a}s ago"))
            }
            _ => {}
        }
    }
    Verdict::Healthy
}

/// What one tick did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// Not wanted: nothing checked, nothing raised.
    Idle,
    Healthy,
    /// Down, and a repair is not due yet.
    Waiting(Duration),
    /// Down (why), repaired.
    Repaired(String),
    /// Down, repair failed; the next attempt is not before `retry_in`.
    Failed {
        error: String,
        retry_in: Duration,
    },
}

#[derive(Default)]
pub struct Watch {
    failures: u32,
    next_try: Option<Instant>,
    /// The `vpn_down` problem, with why: raised on the first failed repair,
    /// kept while it lasts.
    problem: Option<String>,
}

impl Watch {
    /// Why the `vpn_down` problem is raised; `None` when it is not.
    pub fn problem(&self) -> Option<&str> {
        self.problem.as_deref()
    }

    /// One check. The flag says whether the problem was raised or cleared by
    /// this tick.
    pub fn tick(&mut self, now: Instant, probe: &dyn Probe) -> (Outcome, bool) {
        let before = self.problem.is_some();
        let out = self.step(now, probe);
        (out, self.problem.is_some() != before)
    }

    fn step(&mut self, now: Instant, probe: &dyn Probe) -> Outcome {
        if !probe.wanted() {
            self.reset();
            return Outcome::Idle;
        }
        let Verdict::Down(why) = judge(&probe.observe()) else {
            self.reset();
            return Outcome::Healthy;
        };
        if let Some(t) = self.next_try {
            if now < t {
                return Outcome::Waiting(t - now);
            }
        }
        match probe.repair() {
            Ok(()) => {
                // Verified by `vpn::ensure`; the next tick re-observes it.
                self.reset();
                Outcome::Repaired(why)
            }
            Err(e) => {
                self.failures = self.failures.saturating_add(1);
                let wait = (restart_backoff(self.failures) * EVERY.as_secs() as u32).min(MAX_WAIT);
                self.next_try = Some(now + wait);
                let error = format!("{why}: {e}");
                self.problem = Some(error.clone());
                Outcome::Failed {
                    error,
                    retry_in: wait,
                }
            }
        }
    }

    fn reset(&mut self) {
        self.failures = 0;
        self.next_try = None;
        self.problem = None;
    }
}

pub fn enabled() -> bool {
    enabled_from(std::env::var("ZAKURO_VPN_WATCH").ok().as_deref())
}

fn enabled_from(v: Option<&str>) -> bool {
    v.map(str::trim) != Some("0")
}

/// Seconds since the newest handshake, from the peers' handshake *times*
/// (`PeerStatus::last_handshake_secs` is `wg show latest-handshakes`' unix
/// timestamp, not an age). `None` when no peer has handshaken.
///
/// Reading the timestamp as an age made every healthy tunnel look ~1.8e9 s
/// stale: the watcher judged it down and re-ran `vpn::ensure` on every 30 s
/// tick, logging "the mesh tunnel was down; brought it back" forever.
pub fn handshake_age(now: u64, stamps: impl IntoIterator<Item = Option<u64>>) -> Option<u64> {
    stamps
        .into_iter()
        .flatten()
        .filter(|&t| t > 0)
        .max()
        .map(|newest| now.saturating_sub(newest))
}

/// The real host: the agent's desired state, `vpn::route`/`status`/`ensure`.
pub struct HostProbe {
    pub sharing: Box<dyn Fn() -> bool + Send + Sync>,
}

impl Probe for HostProbe {
    fn wanted(&self) -> bool {
        (self.sharing)() && crate::vpn::state::state_path().exists()
    }

    fn observe(&self) -> Observation {
        let up = !matches!(crate::vpn::route(), crate::vpn::Route::None);
        // Live from `wg`, never `vpn::status()`'s connect-time snapshot.
        let peers = crate::vpn::live_peers().unwrap_or_default();
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs());
        Observation {
            up,
            has_peers: !peers.is_empty(),
            handshake_age: handshake_age(now, peers.iter().map(|p| p.last_handshake_secs)),
        }
    }

    fn repair(&self) -> Result<(), String> {
        crate::vpn::ensure(crate::vpn::connector::Preference::Auto)
            .map(|_| ())
            .map_err(|e| e.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::{Cell, RefCell};

    struct Fake {
        wanted: Cell<bool>,
        obs: RefCell<Observation>,
        repair_ok: Cell<bool>,
        repairs: Cell<u32>,
    }

    impl Fake {
        fn new(obs: Observation) -> Self {
            Self {
                wanted: Cell::new(true),
                obs: RefCell::new(obs),
                repair_ok: Cell::new(true),
                repairs: Cell::new(0),
            }
        }
    }

    impl Probe for Fake {
        fn wanted(&self) -> bool {
            self.wanted.get()
        }
        fn observe(&self) -> Observation {
            self.obs.borrow().clone()
        }
        fn repair(&self) -> Result<(), String> {
            self.repairs.set(self.repairs.get() + 1);
            if self.repair_ok.get() {
                Ok(())
            } else {
                Err("wg-quick failed".into())
            }
        }
    }

    fn healthy() -> Observation {
        Observation {
            up: true,
            has_peers: true,
            handshake_age: Some(40),
        }
    }

    fn down() -> Observation {
        Observation {
            up: false,
            has_peers: false,
            handshake_age: None,
        }
    }

    #[test]
    fn the_verdict_covers_missing_interface_stale_and_absent_handshakes() {
        assert_eq!(judge(&healthy()), Verdict::Healthy);
        assert!(matches!(judge(&down()), Verdict::Down(_)));
        let mut o = healthy();
        o.handshake_age = Some(STALE_AFTER_SECS);
        assert_eq!(judge(&o), Verdict::Healthy, "180 s exactly is still fine");
        o.handshake_age = Some(STALE_AFTER_SECS + 1);
        assert!(matches!(judge(&o), Verdict::Down(m) if m.contains("181s")));
        o.handshake_age = None;
        assert!(
            matches!(judge(&o), Verdict::Down(_)),
            "peers but never a handshake"
        );
        o.has_peers = false;
        assert_eq!(
            judge(&o),
            Verdict::Healthy,
            "no peer listed: nothing to judge by"
        );
    }

    #[test]
    fn the_handshake_age_comes_from_the_newest_handshake_time() {
        let now = 1_794_390_000;
        // `wg show latest-handshakes` gives unix times: 9 s and 400 s ago.
        let age = handshake_age(now, [Some(now - 400), Some(now - 9), None]);
        assert_eq!(age, Some(9));
        // A healthy tunnel is judged healthy, not ~1.8e9 s stale.
        let o = Observation {
            up: true,
            has_peers: true,
            handshake_age: age,
        };
        assert_eq!(judge(&o), Verdict::Healthy);
        // Truly stale, and never-handshaken.
        assert_eq!(handshake_age(now, [Some(now - 600)]), Some(600));
        assert_eq!(handshake_age(now, [None, Some(0)]), None);
        // A clock behind the peer's stamp is not a negative age.
        assert_eq!(handshake_age(now, [Some(now + 5)]), Some(0));
    }

    #[test]
    fn a_healthy_tunnel_is_left_alone() {
        let f = Fake::new(healthy());
        let mut w = Watch::default();
        assert_eq!(w.tick(Instant::now(), &f).0, Outcome::Healthy);
        assert_eq!(f.repairs.get(), 0);
        assert_eq!(w.problem(), None);
    }

    #[test]
    fn a_node_not_meant_to_be_on_the_mesh_is_never_touched() {
        let f = Fake::new(down());
        f.wanted.set(false);
        let mut w = Watch::default();
        assert_eq!(w.tick(Instant::now(), &f).0, Outcome::Idle);
        assert_eq!(f.repairs.get(), 0);
    }

    #[test]
    fn a_down_tunnel_is_repaired_at_once() {
        let f = Fake::new(down());
        let mut w = Watch::default();
        assert!(matches!(w.tick(Instant::now(), &f).0, Outcome::Repaired(_)));
        assert_eq!(f.repairs.get(), 1);
        assert_eq!(w.problem(), None, "a repair that worked raises nothing");
    }

    #[test]
    fn failed_repairs_back_off_exponentially_and_raise_the_problem_once() {
        let f = Fake::new(down());
        f.repair_ok.set(false);
        let mut w = Watch::default();
        let t0 = Instant::now();
        let (o, changed) = w.tick(t0, &f);
        assert!(changed, "raised on the first failure");
        let Outcome::Failed { error, retry_in } = o else {
            panic!()
        };
        assert!(
            error.contains("wg-quick failed") && error.contains("interface"),
            "{error}"
        );
        assert_eq!(retry_in, Duration::from_secs(30), "1 x the interval");
        assert!(w.problem().is_some_and(|p| p.contains("wg-quick failed")));
        // Not due: no new attempt.
        let (o, changed) = w.tick(t0 + Duration::from_secs(10), &f);
        assert!(matches!(o, Outcome::Waiting(d) if d == Duration::from_secs(20)));
        assert!(!changed);
        assert_eq!(f.repairs.get(), 1);
        // Due: fails again, and waits twice as long.
        let (o, changed) = w.tick(t0 + Duration::from_secs(30), &f);
        assert!(!changed, "already raised");
        assert!(
            matches!(o, Outcome::Failed { retry_in, .. } if retry_in == Duration::from_secs(60))
        );
        let mut last = Duration::ZERO;
        let mut t = t0 + Duration::from_secs(30);
        for _ in 0..8 {
            t += Duration::from_secs(3600);
            if let (Outcome::Failed { retry_in, .. }, _) = w.tick(t, &f) {
                last = retry_in;
            }
        }
        assert_eq!(last, MAX_WAIT, "capped at 15 minutes");
    }

    #[test]
    fn the_problem_clears_when_the_tunnel_is_healthy_again() {
        let f = Fake::new(down());
        f.repair_ok.set(false);
        let mut w = Watch::default();
        let t0 = Instant::now();
        w.tick(t0, &f);
        assert!(w.problem().is_some());
        // The tunnel comes back by itself.
        *f.obs.borrow_mut() = healthy();
        let (o, changed) = w.tick(t0 + Duration::from_secs(5), &f);
        assert_eq!(o, Outcome::Healthy);
        assert!(changed, "cleared");
        assert_eq!(w.problem(), None);
        // And the backoff is forgotten: the next drop is repaired at once.
        *f.obs.borrow_mut() = down();
        f.repair_ok.set(true);
        assert!(matches!(
            w.tick(t0 + Duration::from_secs(6), &f).0,
            Outcome::Repaired(_)
        ));
    }

    #[test]
    fn a_stale_handshake_triggers_a_repair() {
        let mut o = healthy();
        o.handshake_age = Some(600);
        let f = Fake::new(o);
        let mut w = Watch::default();
        assert!(matches!(w.tick(Instant::now(), &f).0, Outcome::Repaired(_)));
        assert_eq!(f.repairs.get(), 1);
    }

    #[test]
    fn the_watch_is_off_only_for_zero() {
        assert!(!enabled_from(Some("0")));
        assert!(enabled_from(None));
        assert!(enabled_from(Some("1")));
        assert!(enabled_from(Some("")));
    }
}