Skip to main content

vector_core/transport/
host.rs

1//! The process-wide slot for the one active transport instance, its events, and the dial the
2//! bridge runs for every proxied connection.
3
4use std::collections::HashMap;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, Mutex, OnceLock, RwLock};
7
8use super::route::{Dest, Route};
9use super::{BoxedStream, ConnectError, Dialed, Kind, RouteCtx, Ticket, Transport};
10
11const FAILURE_CAP: usize = 128;
12
13struct Failure {
14    at: web_time::Instant,
15    error: ConnectError,
16}
17
18pub struct ActiveTransport {
19    pub kind: Kind,
20    id: u64,
21    /// Fixed for the instance's life: another owner means a new instance.
22    owner: u64,
23    started_prelogin: bool,
24    transport: Arc<dyn Transport>,
25    failures: Mutex<HashMap<String, Failure>>,
26    exits: Mutex<HashMap<String, String>>,
27    identity: Mutex<Option<nostr_sdk::prelude::PublicKey>>,
28}
29
30impl ActiveTransport {
31    pub fn id(&self) -> u64 {
32        self.id
33    }
34
35    pub fn owner(&self) -> u64 {
36        self.owner
37    }
38
39    pub fn started_prelogin(&self) -> bool {
40        self.started_prelogin
41    }
42
43    pub fn transport(&self) -> &Arc<dyn Transport> {
44        &self.transport
45    }
46
47    pub fn last_failure(&self, host: &str) -> Option<(web_time::Instant, ConnectError)> {
48        self.failures.lock().unwrap_or_else(|e| e.into_inner()).get(host).map(|f| (f.at, f.error.clone()))
49    }
50
51    /// The outproxy id the last exit to `host` used.
52    pub fn last_exit(&self, host: &str) -> Option<String> {
53        self.exits.lock().unwrap_or_else(|e| e.into_inner()).get(host).cloned()
54    }
55
56    pub(crate) fn record_failure(&self, host: &str, e: &ConnectError) {
57        self.record(host, Err(e));
58    }
59
60    fn record(&self, host: &str, outcome: Result<&Dialed, &ConnectError>) {
61        let mut failures = self.failures.lock().unwrap_or_else(|e| e.into_inner());
62        match outcome {
63            Ok(dialed) => {
64                failures.remove(host);
65                if let Some(id) = &dialed.outproxy {
66                    let mut exits = self.exits.lock().unwrap_or_else(|e| e.into_inner());
67                    if exits.len() >= 256 && !exits.contains_key(host) {
68                        exits.clear();
69                    }
70                    exits.insert(host.to_string(), id.clone());
71                }
72            }
73            Err(ConnectError::Stale | ConnectError::Cancelled) => {}
74            Err(e) => {
75                if failures.len() >= FAILURE_CAP && !failures.contains_key(host) {
76                    if let Some(oldest) = failures.iter().min_by_key(|(_, f)| f.at).map(|(h, _)| h.clone()) {
77                        failures.remove(&oldest);
78                    }
79                }
80                failures.insert(host.to_string(), Failure { at: web_time::Instant::now(), error: e.clone() });
81            }
82        }
83    }
84
85    /// Whether the live session's egress can run through this instance. One that can't (another
86    /// network chosen, another account's) moves no epoch coming or going: no socket rode it.
87    pub(crate) fn serves_live(&self) -> bool {
88        super::preference() == Some(self.kind) && self.owner == crate::db::live_session_id()
89    }
90
91    /// Record the identity using a pre-login instance. True when a different one used it before.
92    pub(crate) fn note_identity(&self, pk: nostr_sdk::prelude::PublicKey) -> bool {
93        let mut slot = self.identity.lock().unwrap_or_else(|e| e.into_inner());
94        let rotate = matches!(*slot, Some(prev) if prev != pk);
95        *slot = Some(pk);
96        rotate
97    }
98}
99
100static SLOT: RwLock<Option<Arc<ActiveTransport>>> = RwLock::new(None);
101static NEXT_ID: AtomicU64 = AtomicU64::new(1);
102
103pub fn active() -> Option<Arc<ActiveTransport>> {
104    SLOT.read().unwrap_or_else(|e| e.into_inner()).clone()
105}
106
107pub fn active_as<T: Send + Sync + 'static>() -> Option<Arc<T>> {
108    active()?.transport().clone().into_any().downcast::<T>().ok()
109}
110
111/// Install `t`. Err if a slot is occupied: callers uninstall first.
112pub fn activate(t: Arc<dyn Transport>, owner: u64, started_prelogin: bool) -> Result<Arc<ActiveTransport>, String> {
113    let a = Arc::new(ActiveTransport {
114        kind: t.kind(),
115        id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
116        owner,
117        started_prelogin,
118        transport: t,
119        failures: Mutex::new(HashMap::new()),
120        exits: Mutex::new(HashMap::new()),
121        identity: Mutex::new(None),
122    });
123    {
124        let mut slot = SLOT.write().unwrap_or_else(|e| e.into_inner());
125        if slot.is_some() {
126            return Err("A network is already running.".into());
127        }
128        *slot = Some(a.clone());
129    }
130    if !a.serves_live() {
131        notify(TransportEvent::Changed);
132    } else if a.transport().ready() {
133        notify(TransportEvent::Ready { kind: a.kind, instance: a.id, owner, recovered: false });
134        #[cfg(all(feature = "twin-check", not(target_arch = "wasm32")))]
135        super::twins::check_pending();
136    } else {
137        super::bump_epoch();
138        notify(TransportEvent::Changed);
139    }
140    Ok(a)
141}
142
143/// Empty the slot and cut every connection the instance carried. Returns it for shutdown.
144pub fn uninstall() -> Option<Arc<ActiveTransport>> {
145    let a = SLOT.write().unwrap_or_else(|e| e.into_inner()).take()?;
146    if a.serves_live() {
147        super::bump_epoch();
148    }
149    #[cfg(not(target_arch = "wasm32"))]
150    super::bridge::abort_where(|c| c.instance == a.id);
151    notify(TransportEvent::Changed);
152    Some(a)
153}
154
155/// `uninstall`, then shut the instance down; with `join`, wait until the bridge holds none of it.
156pub async fn deactivate(join: bool) {
157    let Some(a) = uninstall() else { return };
158    a.transport().shutdown().await;
159    #[cfg(not(target_arch = "wasm32"))]
160    if join {
161        super::bridge::drain(a.id).await;
162    }
163    #[cfg(target_arch = "wasm32")]
164    let _ = join;
165}
166
167/// The dial behind every proxied connection: a live ticket, the active instance its owner runs,
168/// the shared pre-router, the kind's rules on the live settings, then the kind's own dial.
169pub async fn dial(t: Ticket, dest: Dest, port: u16) -> Result<(BoxedStream, Route, Dialed), ConnectError> {
170    let a = select(&t)?;
171    let host = dest.host();
172    let route = route_now(&a, &dest, port);
173    if let Route::Refuse(r) = route {
174        let e = ConnectError::Refused(r);
175        a.record_failure(&host, &e);
176        return Err(e);
177    }
178    let (stream, dialed) = dial_route(&a, t.lane, &host, &route).await?;
179    Ok((stream, route, dialed))
180}
181
182/// The instance that may serve `t`: live, owned by the ticket's session, of the chosen kind and
183/// ready.
184pub(crate) fn select(t: &Ticket) -> Result<Arc<ActiveTransport>, ConnectError> {
185    if !t.is_live() {
186        return Err(ConnectError::Stale);
187    }
188    let pref = super::preference();
189    let Some(a) = active().filter(|a| a.owner == t.owner && Some(a.kind) == pref) else {
190        return Err(match pref {
191            Some(k) if k != Kind::Clearnet => ConnectError::NotReady(Some(k)),
192            _ => ConnectError::Stale,
193        });
194    };
195    if !a.transport().ready() {
196        return Err(ConnectError::NotReady(Some(a.kind)));
197    }
198    Ok(a)
199}
200
201/// Run the kind's dial for an already-routed connection and record the outcome for `host`.
202pub(crate) async fn dial_route(a: &ActiveTransport, lane: super::Lane, host: &str, route: &Route) -> Result<(BoxedStream, Dialed), ConnectError> {
203    match a.transport().dial(route, lane).await {
204        Ok((stream, dialed)) => {
205            a.record(host, Ok(&dialed));
206            Ok((stream, dialed))
207        }
208        Err(e) => {
209            a.record(host, Err(&e));
210            Err(e)
211        }
212    }
213}
214
215/// Whether the live settings still allow the exit an I2P connection used.
216#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
217pub(crate) fn outproxy_allowed(kind: Kind, id: &str) -> bool {
218    let cfg = super::prefs::live().config(kind);
219    match cfg.downcast_ref::<super::i2p_config::I2pConfig>() {
220        Some(c) => c.exit == super::ExitPolicy::Allow && c.outproxy_list().iter().any(|o| o.id == id && o.enabled),
221        None => true,
222    }
223}
224
225/// The route the live settings give `dest` on this instance right now.
226pub(crate) fn route_now(a: &ActiveTransport, dest: &Dest, port: u16) -> Route {
227    if let Some(r) = super::route::pre_route(a.kind, dest) {
228        return Route::Refuse(r);
229    }
230    let p = super::prefs::live();
231    let (aliases, config) = (p.aliases(), p.config(a.kind));
232    a.transport().route(dest, port, &RouteCtx { aliases: &aliases, config: &config })
233}
234
235#[derive(Clone, Debug, PartialEq, Eq)]
236pub enum TransportEvent {
237    Changed,
238    Ready { kind: Kind, instance: u64, owner: u64, recovered: bool },
239    Lost { kind: Kind, instance: u64, owner: u64 },
240}
241
242fn events() -> &'static tokio::sync::broadcast::Sender<TransportEvent> {
243    static TX: OnceLock<tokio::sync::broadcast::Sender<TransportEvent>> = OnceLock::new();
244    TX.get_or_init(|| tokio::sync::broadcast::channel(64).0)
245}
246
247pub fn subscribe() -> tokio::sync::broadcast::Receiver<TransportEvent> {
248    events().subscribe()
249}
250
251/// Every kind calls this on each `ready()` flip. Ready and Lost move the epoch while the live
252/// egress can run through the instance; an event from an instance that is not the active one, or
253/// whose owner is not live, is dropped.
254pub fn notify(ev: TransportEvent) {
255    match &ev {
256        TransportEvent::Ready { instance, owner, .. } | TransportEvent::Lost { instance, owner, .. } => {
257            let Some(a) = active().filter(|a| a.id == *instance) else { return };
258            if *owner != a.owner || *owner != crate::db::live_session_id() {
259                return;
260            }
261            debug_assert_eq!(
262                a.transport().ready(),
263                matches!(ev, TransportEvent::Ready { .. }),
264                "a kind must report the readiness its event names"
265            );
266            if a.serves_live() {
267                super::bump_epoch();
268            }
269        }
270        TransportEvent::Changed => {}
271    }
272    let _ = events().send(ev);
273    emit_state();
274}
275
276const EMIT_GAP: std::time::Duration = std::time::Duration::from_millis(250);
277
278static EMIT: Mutex<(Option<web_time::Instant>, bool)> = Mutex::new((None, false));
279
280/// At most four `transport_state` events a second; the trailing one always lands, carrying the
281/// state at the moment it is sent.
282fn emit_state() {
283    let wait = {
284        let mut g = EMIT.lock().unwrap_or_else(|e| e.into_inner());
285        let now = web_time::Instant::now();
286        match g.0 {
287            Some(last) if now.duration_since(last) < EMIT_GAP => {
288                if g.1 || !can_trail() {
289                    return;
290                }
291                g.1 = true;
292                Some(EMIT_GAP - now.duration_since(last))
293            }
294            _ => {
295                g.0 = Some(now);
296                None
297            }
298        }
299    };
300    match wait {
301        None => send_view(),
302        Some(delay) => {
303            // Cancelled with a short-lived caller runtime, even before its first poll: the next
304            // event must still emit.
305            let pending = TrailingPending;
306            let trailing = async move {
307                let pending = pending;
308                crate::rt::time::sleep(delay).await;
309                EMIT.lock().unwrap_or_else(|e| e.into_inner()).0 = Some(web_time::Instant::now());
310                drop(pending);
311                send_view();
312            };
313            // The process-lifetime runtime when one exists, so the trailing event outlives the
314            // caller's (Android background sync); a Clearnet-only process never builds it for this.
315            #[cfg(not(target_arch = "wasm32"))]
316            if let Some(rt) = super::runtime::built() {
317                // spawn-detached: emits the live view once the gap passes; reads no account state.
318                rt.spawn(trailing);
319                return;
320            }
321            // spawn-detached: emits the live view once the gap passes; reads no account state.
322            crate::rt::spawn(trailing);
323        }
324    }
325}
326
327fn can_trail() -> bool {
328    #[cfg(not(target_arch = "wasm32"))]
329    if super::runtime::built().is_some() {
330        return true;
331    }
332    crate::rt::can_spawn()
333}
334
335/// The trailing emit is armed while this lives.
336struct TrailingPending;
337
338impl Drop for TrailingPending {
339    fn drop(&mut self) {
340        EMIT.lock().unwrap_or_else(|e| e.into_inner()).1 = false;
341    }
342}
343
344fn send_view() {
345    crate::traits::emit_event("transport_state", &super::status::view());
346}