gent-daemon 0.1.2

Local daemon, storage and synchronization for Gent chat clusters.
Documentation
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Exact local dirty sets; relay hints never advance stream cursors.
use super::*;
use gent_protocol::transport_watch::{Interest, MAX_INTERESTS, Subscription, VERSION};

#[derive(Default)]
pub(super) struct Hints {
    state: Mutex<State>,
    pub(super) subscription_changed: Notify,
}
#[derive(Default)]
struct State {
    passive: bool,
    interests: Vec<Interest>,
    dirty: BTreeSet<Vec<u8>>,
    full: bool,
    control: bool,
    reconnected: bool,
}
impl Hints {
    pub(super) fn subscribe(&self, streams: &[Stream]) {
        let interests: Vec<_> = streams
            .iter()
            .map(|s| Interest {
                mailbox: URL_SAFE_NO_PAD.encode(&s.group),
                outgoing: s.outgoing,
            })
            .collect();
        let mut state = self.state.lock().expect("sync hints poisoned");
        if state.interests != interests {
            state.interests = interests;
            self.subscription_changed.notify_one();
            state.full = true;
        }
    }
    pub(super) fn set_passive(&self, passive: bool) {
        self.state.lock().expect("sync hints poisoned").passive = passive;
    }
    pub(super) fn passive(&self) -> bool {
        let state = self.state.lock().expect("sync hints poisoned");
        state.passive
    }
    pub(super) fn subscription(&self, passive: bool) -> Subscription {
        let state = self.state.lock().expect("sync hints poisoned");
        let all = passive && state.interests.len() > MAX_INTERESTS;
        let end = if all {
            0
        } else {
            state.interests.len().min(MAX_INTERESTS)
        };
        Subscription {
            version: VERSION,
            all,
            interests: state.interests[..end].to_vec(),
        }
    }

    #[cfg(test)]
    fn interests(&self) -> Vec<Interest> {
        self.state
            .lock()
            .expect("sync hints poisoned")
            .interests
            .clone()
    }
    pub(super) fn all(&self) {
        let mut state = self.state.lock().expect("sync hints poisoned");
        state.full = true;
        state.control = true;
    }
    pub(super) fn reconnected(&self) {
        let mut state = self.state.lock().expect("sync hints poisoned");
        state.full = true;
        state.control = true;
        state.reconnected = true;
    }
    pub(super) fn take_reconnected(&self) -> bool {
        std::mem::take(&mut self.state.lock().expect("sync hints poisoned").reconnected)
    }
    pub(super) fn control(&self) -> bool {
        std::mem::take(&mut self.state.lock().expect("sync hints poisoned").control)
    }
    pub(super) fn changed(&self, streams: &[Interest]) -> bool {
        let mut state = self.state.lock().expect("sync hints poisoned");
        let mut changed = false;
        for stream in streams {
            if state.interests.contains(stream)
                && let Ok(group) = URL_SAFE_NO_PAD.decode(&stream.mailbox)
            {
                changed |= state.dirty.insert(group);
            }
        }
        changed
    }
    pub(super) fn take(&self) -> (bool, BTreeSet<Vec<u8>>) {
        let mut state = self.state.lock().expect("sync hints poisoned");
        (
            std::mem::take(&mut state.full),
            std::mem::take(&mut state.dirty),
        )
    }
}

pub(super) struct Schedule {
    next_full: Instant,
    pending: BTreeSet<Vec<u8>>,
    peer_repair: BTreeSet<Vec<u8>>,
    cursor: usize,
    pub(super) timed_repair: bool,
}
impl Default for Schedule {
    fn default() -> Self {
        Self {
            next_full: Instant::now(),
            pending: BTreeSet::new(),
            peer_repair: BTreeSet::new(),
            cursor: 0,
            timed_repair: false,
        }
    }
}

pub(super) struct Selection {
    pub(super) streams: Vec<Stream>,
    pub(super) peers: BTreeSet<Vec<u8>>,
}

impl Schedule {
    pub(super) fn select(
        &mut self,
        streams: &[Stream],
        hints: &Hints,
        work: &MailboxWork,
        retries: &BTreeMap<Vec<u8>, Retry>,
        connected: bool,
    ) -> Selection {
        let now = Instant::now();
        let (full, dirty) = hints.take();
        // A reconnect, explicit hint or follow-up to an active transfer can
        // carry a waiting message. Fetch those without a conditional preflight.
        self.timed_repair = now >= self.next_full
            && !full
            && dirty.is_empty()
            && self.pending.is_empty()
            && retries.is_empty();
        self.pending.extend(dirty);
        self.pending.extend(work.ready.iter().cloned());
        if full || now >= self.next_full {
            if full || !connected || !hints.passive() {
                self.pending.extend(streams.iter().map(|s| s.group.clone()));
            } else {
                // A lost receipt or relay rollback needs repair while a writer
                // still owns unsigned history. Drained, subscribed streams sleep.
                self.pending.extend(work.unconfirmed.iter().cloned());
            }
            self.peer_repair.extend(
                streams
                    .iter()
                    .filter(|s| {
                        s.outgoing && !s.configuration && work.unconfirmed.contains(&s.group)
                    })
                    .map(|s| s.group.clone()),
            );
            // Small deterministic per-process jitter avoids synchronized scans.
            self.next_full = now
                + Duration::from_secs(if connected {
                    30 + u64::from(std::process::id() % 7)
                } else {
                    5
                });
        }
        // A partial peer batch can drain its uploaded suffix on the next turn.
        // Re-read the durable receipt before scheduling another attempt.
        self.peer_repair
            .retain(|g| work.unconfirmed.contains(g) && streams.iter().any(|s| &s.group == g));
        self.pending.extend(self.peer_repair.iter().cloned());
        self.pending.extend(
            retries
                .iter()
                .filter(|(_, r)| r.at <= now)
                .map(|(g, _)| g.clone()),
        );
        self.pending
            .retain(|g| streams.iter().any(|s| &s.group == g));
        let selected: Vec<_> = streams
            .iter()
            .enumerate()
            .cycle()
            .skip(self.cursor.min(streams.len()))
            .take(streams.len())
            .filter(|(_, s)| {
                self.pending.contains(&s.group) && retries.get(&s.group).is_none_or(|r| r.at <= now)
            })
            .take(32)
            .map(|(index, s)| (index, s.clone()))
            .collect();
        if let Some((last, _)) = selected.last() {
            self.cursor = (last + 1) % streams.len();
        }
        let mut peers = BTreeSet::new();
        for (_, s) in &selected {
            self.pending.remove(&s.group);
            let repair = self.peer_repair.remove(&s.group)
                || (retries.contains_key(&s.group) && work.unconfirmed.contains(&s.group));
            if s.outgoing && !s.configuration && (repair || work.ready.contains(&s.group)) {
                peers.insert(s.group.clone());
            }
        }
        Selection {
            streams: selected.into_iter().map(|(_, s)| s).collect(),
            peers,
        }
    }
    pub(super) fn again(&mut self, group: Vec<u8>) {
        self.pending.insert(group);
    }
    pub(super) fn peer_progress(&mut self, group: Vec<u8>) {
        self.peer_repair.insert(group);
    }
    pub(super) fn next_full(&self) -> Instant {
        self.next_full
    }
    pub(super) fn has_ready(&self, retries: &BTreeMap<Vec<u8>, Retry>) -> bool {
        let now = Instant::now();
        self.pending
            .iter()
            .any(|g| retries.get(g).is_none_or(|r| r.at <= now))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[tokio::test(start_paused = true)]
    async fn uploaded_streams_wait_for_work_receipt_hint_reconnect_or_safety_deadline() {
        let streams = [Stream {
            group: vec![1],
            outgoing: true,
            configuration: true,
        }];
        let hints = Hints::default();
        hints.subscribe(&streams);
        let mut schedule = Schedule::default();
        let retries = BTreeMap::new();
        let mut select = |queued, connected| {
            schedule
                .select(
                    &streams,
                    &hints,
                    &MailboxWork {
                        ready: queued,
                        ..Default::default()
                    },
                    &retries,
                    connected,
                )
                .streams
                .len()
        };
        assert_eq!(select(BTreeSet::new(), true), 1);
        tokio::time::advance(Duration::from_secs(5)).await;
        assert_eq!(select(BTreeSet::new(), true), 0);
        assert_eq!(select(BTreeSet::from([vec![1]]), true), 1);
        assert_eq!(select(BTreeSet::new(), true), 0);
        assert!(hints.changed(&hints.interests()));
        assert_eq!(select(BTreeSet::new(), true), 1);
        tokio::time::advance(Duration::from_secs(37)).await;
        assert_eq!(select(BTreeSet::new(), true), 1);
        hints.all();
        assert_eq!(select(BTreeSet::new(), false), 1);
        tokio::time::advance(Duration::from_secs(4)).await;
        assert_eq!(select(BTreeSet::new(), false), 0);
        tokio::time::advance(Duration::from_secs(1)).await;
        assert_eq!(select(BTreeSet::new(), false), 1);
        hints.reconnected();
        assert!(hints.take_reconnected());
        assert!(!hints.take_reconnected());
        assert_eq!(select(BTreeSet::new(), true), 1);
    }
    #[tokio::test(start_paused = true)]
    async fn acknowledged_watch_sleeps_until_a_change_or_an_unsigned_upload_needs_repair() {
        let streams: Vec<_> = (0..3)
            .map(|n| Stream {
                group: vec![n],
                outgoing: n != 0,
                configuration: n == 2,
            })
            .collect();
        let hints = Hints::default();
        hints.subscribe(&streams);
        hints.set_passive(true);
        let mut schedule = Schedule::default();
        let mut work = MailboxWork::default();
        let select = |s: &mut Schedule, w: &MailboxWork| {
            s.select(&streams, &hints, w, &BTreeMap::new(), true)
        };
        assert_eq!(select(&mut schedule, &work).streams.len(), 3);
        tokio::time::advance(Duration::from_secs(3600)).await;
        assert!(select(&mut schedule, &work).streams.is_empty());
        assert!(hints.changed(&hints.interests()[..1]));
        assert_eq!(select(&mut schedule, &work).streams[0].group, vec![0]);
        work.unconfirmed.insert(vec![2]);
        tokio::time::advance(Duration::from_secs(40)).await;
        let repair = select(&mut schedule, &work);
        assert_eq!(repair.streams.len(), 1);
        assert_eq!(repair.streams[0].group, vec![2]);
        assert!(repair.peers.is_empty());
        hints.reconnected();
        assert_eq!(select(&mut schedule, &work).streams.len(), 3);
    }

    #[test]
    fn repair_retries_uploaded_peer_batches_until_durably_confirmed() {
        let stream = Stream {
            group: vec![1],
            outgoing: true,
            configuration: false,
        };
        let streams = std::slice::from_ref(&stream);
        let hints = Hints::default();
        hints.subscribe(streams);
        let mut work = MailboxWork::default();
        work.unconfirmed.insert(stream.group.clone());
        let mut schedule = Schedule::default();
        let select = |s: &mut Schedule, w: &MailboxWork| {
            s.select(streams, &hints, w, &BTreeMap::new(), true)
        };
        assert!(select(&mut schedule, &work).peers.contains(&stream.group));
        // A sleeping recipient and a successful cloud upload incur no extra turn.
        assert!(select(&mut schedule, &work).streams.is_empty());
        hints.changed(&hints.interests());
        let hint = select(&mut schedule, &work);
        assert_eq!(hint.streams.len(), 1);
        assert!(hint.peers.is_empty());
        schedule.next_full = Instant::now();
        assert!(select(&mut schedule, &work).peers.contains(&stream.group));
        hints.reconnected();
        assert!(select(&mut schedule, &work).peers.contains(&stream.group));
        // Successful peer batches resume immediately while ciphertext remains.
        schedule.peer_progress(stream.group.clone());
        assert!(select(&mut schedule, &work).peers.contains(&stream.group));
        schedule.peer_progress(stream.group.clone());
        work.unconfirmed.clear();
        assert!(select(&mut schedule, &work).streams.is_empty());
    }

    #[test]
    fn continuously_queued_peers_cannot_starve_later_streams() {
        let streams: Vec<_> = (0..100)
            .map(|i| Stream {
                group: vec![i],
                outgoing: true,
                configuration: false,
            })
            .collect();
        let work = MailboxWork {
            ready: streams.iter().map(|s| s.group.clone()).collect(),
            ..Default::default()
        };
        let hints = Hints::default();
        let mut schedule = Schedule::default();
        let mut seen = BTreeSet::new();
        for _ in 0..4 {
            let selected = schedule
                .select(&streams, &hints, &work, &BTreeMap::new(), true)
                .streams;
            assert_eq!(selected.len(), 32);
            seen.extend(selected.into_iter().map(|s| s.group));
        }
        assert_eq!(seen.len(), 100);
    }
    #[test]
    fn exact_stream_hints_ignore_other_nodes_and_full_scan_recovers_lost_hints() {
        let streams: Vec<_> = (0..3)
            .map(|i| Stream {
                group: vec![i],
                outgoing: false,
                configuration: false,
            })
            .collect();
        let hints = Hints::default();
        hints.subscribe(&streams);
        let mut schedule = Schedule::default();
        let retries = BTreeMap::new();
        assert_eq!(
            schedule
                .select(&streams, &hints, &MailboxWork::default(), &retries, true)
                .streams
                .len(),
            3
        );
        assert!(
            schedule
                .select(&streams, &hints, &MailboxWork::default(), &retries, true)
                .streams
                .is_empty()
        );
        assert!(!hints.changed(&[Interest {
            mailbox: URL_SAFE_NO_PAD.encode([99]),
            outgoing: false
        }]));
        hints.changed(&[Interest {
            mailbox: URL_SAFE_NO_PAD.encode([1]),
            outgoing: false,
        }]);
        assert_eq!(
            schedule
                .select(&streams, &hints, &MailboxWork::default(), &retries, true)
                .streams[0]
                .group,
            vec![1]
        );
        schedule.next_full = Instant::now();
        assert_eq!(
            schedule
                .select(&streams, &hints, &MailboxWork::default(), &retries, true)
                .streams
                .len(),
            3
        );
    }
}