gent-daemon 0.1.1

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
//! Fair allocation of a bounded number of helper sockets, independent of cloud
//! reconciliation. One alias is tried per registration, across all peer pairs.
use super::*;
use std::sync::Weak;
use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard, watch};

const REGISTRATION_WINDOW: Duration = Duration::from_secs(8);

#[derive(Clone)]
pub(super) struct Source {
    pub(super) offer: HelperOffer,
    pub(super) operator: (EndpointId, [u8; 32]),
    pub(super) expiry: i64,
}
impl Source {
    fn matches(&self, slot: &Slot) -> bool {
        self.operator == slot.operator && same_service(&self.offer, &slot.offer)
    }
}

pub(super) struct Slot {
    operator: (EndpointId, [u8; 32]),
    locator: watch::Sender<i64>,
    offer: Arc<HelperOffer>,
    available: watch::Sender<bool>,
    bound: Arc<Mutex<Option<Arc<Auxiliary>>>>,
    last_good: Instant,
    worker: JoinHandle<()>,
}
impl Drop for Slot {
    fn drop(&mut self) {
        self.available.send_replace(false);
        if let Some(aux) = self.get() {
            aux.withdraw_registration();
        }
        self.worker.abort();
    }
}
impl Slot {
    pub(super) fn get(&self) -> Option<Arc<Auxiliary>> {
        self.bound.lock().expect("helper endpoint poisoned").clone()
    }
}

#[derive(Default)]
pub(super) struct Helpers {
    pub(super) active: BTreeMap<String, Slot>,
    pub(super) draining: Vec<Slot>,
    offers: BTreeMap<String, Source>,
    attempts: BTreeMap<String, (u64, usize)>,
    sequence: u64,
    last_rotation: Option<Instant>,
}

impl Helpers {
    pub(super) fn update(&mut self, offers: BTreeMap<String, Source>, wakeup: &Notify) {
        self.offers = offers;
        self.attempts.retain(|id, _| self.offers.contains_key(id));
        self.draining.retain(|slot| {
            slot.get().is_some_and(|a| {
                a.prune();
                a.keep_direct()
            })
        });
        for (id, mut slot) in std::mem::take(&mut self.active) {
            let aux = slot.get();
            if let Some(aux) = &aux {
                aux.prune();
            }
            if let Some(source) = self.offers.get(&id).filter(|s| s.matches(&slot))
                && !slot.worker.is_finished()
                && (registration::deadline(source.expiry).is_some()
                    || aux.as_ref().is_some_and(|a| a.retained()))
            {
                slot.locator.send_if_modified(|at| {
                    if *at == source.expiry {
                        return false;
                    }
                    *at = source.expiry;
                    true
                });
                if aux.is_some_and(|a| a.registration().is_some()) {
                    slot.last_good = Instant::now();
                }
                self.active.insert(id, slot);
            } else {
                slot.available.send_replace(false);
                if let Some(aux) = aux {
                    if aux.withdraw_registration() {
                        wakeup.notify_one();
                    }
                    if aux.keep_direct() && self.draining.len() < MAX_HELPERS {
                        self.draining.push(slot);
                    }
                }
            }
        }
    }

    pub(super) fn allocate(&mut self, factory: &Factory) {
        // An offer returning after an idle expiry can reuse its existing UDP
        // socket, including the proved connection and its TLS registration.
        let mut index = 0;
        while index < self.draining.len() {
            let slot = &self.draining[index];
            if self.active.len() < MAX_HELPERS
                && self
                    .offers
                    .get(&slot.offer.helper_node)
                    .is_some_and(|s| s.matches(slot) && registration::deadline(s.expiry).is_some())
            {
                let mut slot = self.draining.swap_remove(index);
                slot.locator
                    .send_replace(self.offers[&slot.offer.helper_node].expiry);
                slot.available.send_replace(true);
                slot.last_good = Instant::now();
                self.active.insert(slot.offer.helper_node.clone(), slot);
            } else {
                index += 1;
            }
        }
        let crowded = self.offers.iter().any(|(id, s)| {
            !self.active.contains_key(id) && registration::deadline(s.expiry).is_some()
        });
        if self
            .last_rotation
            .is_none_or(|t| t.elapsed() >= REGISTRATION_WINDOW)
        {
            let mut stale: Vec<_> = self
                .active
                .iter()
                .filter(|(_, s)| {
                    (crowded || s.offer.urls.len() > 1)
                        && s.last_good.elapsed() >= REGISTRATION_WINDOW
                        && s.get()
                            .is_none_or(|a| a.registration().is_none() && !a.in_use())
                })
                .map(|(id, s)| (s.last_good, id.clone()))
                .collect();
            stale.sort();
            for (_, id) in stale.into_iter().take(2) {
                self.active.remove(&id);
                self.last_rotation = Some(Instant::now());
            }
        }
        let mut waiting: Vec<_> = self
            .offers
            .keys()
            .filter(|id| !self.active.contains_key(*id))
            .collect();
        waiting.sort_by_key(|id| self.attempts.get(*id).map(|(seq, _)| *seq));
        for id in waiting {
            if self.active.len() + self.draining.len() >= MAX_HELPERS {
                break;
            }
            let source = &self.offers[id];
            if registration::deadline(source.expiry).is_none() {
                continue;
            }
            let offer = &source.offer;
            // A repeated signed description of one TLS service must never create
            // another registration for this identity, even under another node ID.
            if self
                .active
                .values()
                .chain(&self.draining)
                .any(|s| s.offer.generation == offer.generation)
            {
                continue;
            }
            let (seq, next) = self.attempts.entry(id.clone()).or_default();
            let alias = offer.urls[*next % offer.urls.len()].clone();
            *next = next.wrapping_add(1);
            self.sequence += 1;
            *seq = self.sequence;
            self.active.insert(id.clone(), factory.start(source, alias));
        }
    }
}

pub(super) struct Factory {
    key: SecretKey,
    udp: bool,
    store: SharedStore,
    metrics: Arc<Metrics>,
    wakeup: Arc<Notify>,
    incoming: Arc<Semaphore>,
    files: Arc<Semaphore>,
    owners: Mutex<BTreeMap<[u8; 32], Weak<AsyncMutex<()>>>>,
}
impl Factory {
    fn start(&self, source: &Source, alias: RelayUrl) -> Slot {
        let offer = Arc::new(source.offer.clone());
        let operator = source.operator;
        let (locator, mut expiry) = watch::channel(source.expiry);
        let authority = Authority {
            offer: offer.clone(),
            operator,
            locator: expiry.clone(),
        };
        let bound = Arc::new(Mutex::new(None));
        let (available, mut active) = watch::channel(true);
        let ready = bound.clone();
        let key = self.key.clone();
        let store = self.store.clone();
        let metrics = self.metrics.clone();
        let wake = self.wakeup.clone();
        let (incoming, files) = (self.incoming.clone(), self.files.clone());
        let udp = self.udp;
        let url = alias;
        let owner = {
            let mut owners = self.owners.lock().expect("helper socket owners poisoned");
            owners.retain(|_, v| v.strong_count() > 0);
            let weak = owners.entry(offer.generation).or_default();
            weak.upgrade().unwrap_or_else(|| {
                let owner = Arc::new(AsyncMutex::new(()));
                *weak = Arc::downgrade(&owner);
                owner
            })
        };
        let worker = tokio::spawn(async move {
            let permit = owner.lock_owned().await;
            let aux = loop {
                if registration::deadline(*expiry.borrow()).is_none() {
                    return;
                }
                if let Ok(aux) = Auxiliary::bind(
                    key.clone(),
                    authority.clone(),
                    &url,
                    udp,
                    store.clone(),
                    metrics.clone(),
                    active.clone(),
                )
                .await
                {
                    break Arc::new(aux);
                }
                tokio::time::sleep(RETRY).await;
            };
            let _lease = SocketLease(aux.endpoint.clone(), Some(permit));
            let mut status = aux.endpoint.home_relay_status();
            let mut report = aux.endpoint.net_report();
            *ready.lock().expect("helper endpoint poisoned") = Some(aux.clone());
            let watch = async {
                let mut new_report = false;
                let mut relay_enabled = true;
                loop {
                    if aux.update_registration(report.get().as_ref(), new_report) {
                        wake.notify_one();
                    }
                    let until =
                        registration::deadline(*expiry.borrow_and_update()).max(aux.live_until());
                    let enabled = *active.borrow_and_update() && until.is_some();
                    if enabled != relay_enabled {
                        if enabled {
                            aux.endpoint
                                .insert_relay(url.clone(), Arc::new(aux.relay_config.clone()))
                                .await;
                        } else {
                            if aux.withdraw_registration() {
                                wake.notify_one();
                            }
                            aux.endpoint.remove_relay(&url).await;
                        }
                        relay_enabled = enabled;
                    }
                    new_report = false;
                    tokio::select! {
                        _=aux.reschedule.notified()=>{},
                        changed=active.changed()=> if changed.is_err() {break},
                        changed=expiry.changed()=> if changed.is_err() {break},
                        s=status.updated() => if s.is_err() {break},
                        r=report.updated() => { if r.is_err() {break;} new_report = true; },
                        _=async {if let Some(t)=until { tokio::time::sleep_until(t).await }} , if enabled => {}
                    }
                }
            };
            tokio::select! { _=watch=>{}, _=aux.renew_home()=>{}, _=aux.clone().listen(incoming,files)=>{} }
        });
        Slot {
            operator,
            locator,
            offer,
            available,
            bound,
            last_good: Instant::now(),
            worker,
        }
    }
}

// Finish closing the previous socket before another alias of this TLS
// service is allowed to register the same local endpoint ID.
struct SocketLease(Endpoint, Option<OwnedMutexGuard<()>>);
impl Drop for SocketLease {
    fn drop(&mut self) {
        let ep = self.0.clone();
        let permit = self.1.take();
        tokio::spawn(async move {
            ep.close().await;
            drop(permit);
        });
    }
}

impl Factory {
    pub(super) fn new(
        key: SecretKey,
        udp: bool,
        store: SharedStore,
        metrics: Arc<Metrics>,
        wakeup: Arc<Notify>,
    ) -> Self {
        Self {
            key,
            udp,
            store,
            metrics,
            wakeup,
            incoming: Arc::new(Semaphore::new(quic::MAX_LINKS)),
            files: Arc::new(Semaphore::new(2)),
            owners: Mutex::default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn saturated_pool_rotates_failed_slots_without_restarting_the_others() -> Result<()> {
        use std::os::unix::fs::PermissionsExt;
        let home = tempfile::tempdir()?;
        std::fs::set_permissions(home.path(), std::fs::Permissions::from_mode(0o700))?;
        config::initialize(home.path(), "helper-slot-test")?;
        let store = Arc::new(Mutex::new(Store::open(home.path())?));
        let notify = Arc::new(Notify::new());
        let factory = Factory::new(
            SecretKey::generate(),
            false,
            store,
            Arc::default(),
            notify.clone(),
        );
        // Run the allocator without yielding to its background bind tasks.
        let operator = (SecretKey::generate().public(), [5; 32]);
        let offers: BTreeMap<_, _> = (0..=MAX_HELPERS)
            .map(|n| {
                let node = format!("test-{n:02}");
                (
                    node.clone(),
                    Source {
                        operator,
                        expiry: crate::store::now() + 180,
                        offer: HelperOffer {
                            helper_node: node,
                            urls: vec![
                                "https://127.0.0.1:7001/".parse().unwrap(),
                                "https://127.0.0.1:7002/".parse().unwrap(),
                            ],
                            cert_der: vec![n as u8],
                            generation: [n as u8; 32],
                            qad_port: None,
                        },
                    },
                )
            })
            .collect();
        let mut helpers = Helpers::default();
        helpers.update(offers.clone(), &notify);
        helpers.allocate(&factory);
        assert_eq!(helpers.active.len(), MAX_HELPERS);
        assert!(!helpers.active.contains_key("test-16"));
        let workers: BTreeSet<_> = helpers.active.values().map(|s| s.worker.id()).collect();
        for slot in helpers.active.values_mut() {
            slot.last_good = Instant::now() - REGISTRATION_WINDOW;
        }
        helpers.allocate(&factory);
        assert!(helpers.active.contains_key("test-16"));
        assert_eq!(helpers.active.len(), MAX_HELPERS);
        assert_eq!(
            helpers
                .active
                .values()
                .filter(|s| workers.contains(&s.worker.id()))
                .count(),
            MAX_HELPERS - 2
        );
        assert!(helpers.attempts.values().any(|(_, alias)| *alias == 2));
        let chosen = helpers.sequence;
        helpers.allocate(&factory);
        assert_eq!(chosen, helpers.sequence);
        let mut duplicate = offers["test-16"].clone();
        duplicate.offer.helper_node = "another-name".into();
        helpers.update(
            [
                ("another-name".into(), duplicate),
                ("test-16".into(), offers["test-16"].clone()),
            ]
            .into(),
            &notify,
        );
        helpers.allocate(&factory);
        assert_eq!(helpers.active.len(), 1);
        Ok(())
    }
}