Skip to main content

vector_core/transport/
cycle.rs

1//! Moving relay sockets onto the network now in use. Runs on the embedding app's runtime, never
2//! the transport runtime: nostr-sdk spawns a relay's tasks on the runtime that connects it.
3
4use std::sync::Mutex;
5
6use nostr_sdk::prelude::{Client, RelayStatus};
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum CycleScope {
10    /// New circuit, bridges, circuit mode: the main client's relays reconnect at once.
11    Circuits,
12    /// The fail-closed step of a network switch: everything that pools or authenticates
13    /// outside a guarded socket is dropped.
14    Switch,
15    /// The network became ready: revive every relay the switch left dead.
16    Kick,
17}
18
19const TRACK_CAP: usize = 8;
20
21struct Tracked {
22    id: u64,
23    owner: u64,
24    client: Client,
25}
26
27static TRACKED: Mutex<Vec<Tracked>> = Mutex::new(Vec::new());
28static TRACK_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
29
30/// A client outside the session's own (Android background, device transfer) that `Kick` revives
31/// too, until [`untrack`]; shut-down clients and those of a session no longer live drop out.
32pub fn track(client: &Client) -> u64 {
33    let id = TRACK_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
34    let mut v = TRACKED.lock().unwrap_or_else(|e| e.into_inner());
35    prune(&mut v);
36    if v.len() >= TRACK_CAP {
37        v.remove(0);
38    }
39    v.push(Tracked { id, owner: crate::db::current_session_id(), client: client.clone() });
40    id
41}
42
43/// A tracked client that is done: Kick must not bring a merely disconnected one back.
44pub fn untrack(id: u64) {
45    TRACKED.lock().unwrap_or_else(|e| e.into_inner()).retain(|t| t.id != id);
46}
47
48fn prune(v: &mut Vec<Tracked>) {
49    let live = crate::db::live_session_id();
50    v.retain(|t| !t.client.is_shutdown() && t.owner == live);
51}
52
53fn tracked() -> Vec<Client> {
54    let mut v = TRACKED.lock().unwrap_or_else(|e| e.into_inner());
55    prune(&mut v);
56    v.iter().map(|t| t.client.clone()).collect()
57}
58
59#[cfg(test)]
60pub(crate) fn tracked_count() -> usize {
61    tracked().len()
62}
63
64pub async fn cycle_all(scope: CycleScope) {
65    match scope {
66        CycleScope::Circuits => {
67            // First: pooled HTTP connections must not keep riding the circuits being left while
68            // the relays reconnect.
69            crate::net::forget_clients();
70            cycle_circuits().await;
71            crate::net::forget_clients();
72        }
73        CycleScope::Switch => {
74            crate::signer::suspend_bunker().await;
75            crate::community::transport::on_transport_switch();
76            crate::community::transport::clear_plane_pool();
77            #[cfg(feature = "xdc")]
78            crate::xdc::mesh::retire_live_if_idle().await;
79            crate::net::forget_clients();
80        }
81        CycleScope::Kick => {
82            let mut clients: Vec<Client> = crate::state::nostr_client().into_iter().collect();
83            clients.extend(tracked());
84            futures_util::future::join_all(clients.iter().map(kick)).await;
85            crate::signer::resume_bunker().await;
86        }
87    }
88}
89
90/// Every relay of the main client, GOSSIP-only ones included, reconnects through the current
91/// transport. Per-relay `try_connect`: `client.connect()` can wedge a relay in Pending.
92async fn cycle_circuits() {
93    let Some(client) = crate::state::nostr_client() else { return };
94    let relays = client.relays().all().await;
95    crate::log_info!("[Tor] cycling {} relay connection(s) onto new transport...", relays.len());
96    let budget = super::budget(super::Op::RelayConnect, std::time::Duration::from_secs(15));
97    for relay in relays.values() {
98        relay.disconnect();
99    }
100    // Let the old connection tasks see the terminate signal: a reconnect while one still runs
101    // gets the fresh socket dropped on arrival.
102    crate::rt::time::sleep(std::time::Duration::from_millis(500)).await;
103    futures_util::future::join_all(relays.into_values().map(|relay| async move {
104        let _ = relay.try_connect().timeout(budget).await;
105    }))
106    .await;
107    crate::log_info!("[Tor] relay transport switch complete");
108}
109
110/// A relay a revival pass should try: connectable (Initialized when added while the network was
111/// down, Terminated once its socket died) and not refused by policy, which no retry changes.
112pub fn revivable(relay: &nostr_sdk::prelude::Relay) -> bool {
113    matches!(relay.status(), RelayStatus::Initialized | RelayStatus::Terminated | RelayStatus::Sleeping)
114        && super::refuses(relay.url().as_str()).is_none()
115}
116
117async fn kick(client: &Client) {
118    let budget = super::budget(super::Op::RelayConnect, std::time::Duration::from_secs(15));
119    let relays = client.relays().all().await;
120    futures_util::future::join_all(relays.into_values().filter(revivable).map(|relay| async move {
121        let _ = relay.try_connect().timeout(budget).await;
122    }))
123    .await;
124}