agentmux_srv_core/muxbus/cloud_subscriber/
session.rs1use std::sync::{Arc, Mutex};
10use std::time::{Duration, Instant};
11
12use std::collections::HashSet;
13
14use super::supervisor::beat;
15use super::{shared_token_now, CLIENT_PING_INTERVAL_SECS};
16use crate::backend::storage::store::Store;
17
18pub(super) fn http_client() -> reqwest::Client {
21 crate::http_client::client_with(|b| b.user_agent(crate::muxbus::relay::USER_AGENT).connect_timeout(Duration::from_secs(10)))
22}
23
24#[derive(Clone, Copy)]
26pub(super) struct SessionLimits {
27 pub(super) connect: Duration,
29 pub(super) silence: Duration,
34 pub(super) check_every: Duration,
36}
37
38impl Default for SessionLimits {
39 fn default() -> Self {
40 SessionLimits {
41 connect: Duration::from_secs(30),
42 silence: Duration::from_secs(2 * CLIENT_PING_INTERVAL_SECS + 60),
43 check_every: Duration::from_secs(30),
44 }
45 }
46}
47
48pub(super) struct Watchdog {
51 last_heard: Instant,
52 silence: Duration,
53 check: tokio::time::Interval,
54}
55
56impl Watchdog {
57 pub(super) async fn new(limits: SessionLimits) -> Self {
58 let mut check = tokio::time::interval(limits.check_every);
59 check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
60 check.tick().await; Watchdog { last_heard: Instant::now(), silence: limits.silence, check }
62 }
63
64 pub(super) fn heard(&mut self) {
66 self.last_heard = Instant::now();
67 }
68
69 pub(super) async fn silent(&mut self) -> String {
72 loop {
73 self.check.tick().await;
74 beat();
75 if self.last_heard.elapsed() > self.silence {
76 return format!("no word from the relay for {}s", self.last_heard.elapsed().as_secs());
77 }
78 }
79 }
80}
81
82pub(super) fn release_in_background(id: String, base: String, token: String, http: reqwest::Client, mstore: Arc<Store>, agents: Arc<Mutex<HashSet<String>>>) {
84 tokio::spawn(async move {
85 let token = shared_token_now(&mstore, &token).await;
86 let still_gone = || !agents.lock().unwrap().contains(&id);
88 crate::muxbus::wan_lease::release(&base, &id, &token, &http, still_gone).await
89 });
90}