Skip to main content

vector_core/transport/
status.rs

1//! Serde views shared by every shell (Tauri and Vector Web), with the reason codes and texts.
2
3use std::sync::Mutex;
4
5use serde::Serialize;
6
7use super::{Kind, TransportState};
8
9#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
10pub struct Reason {
11    pub code: String,
12    pub text: String,
13}
14
15impl Reason {
16    pub fn new(code: &str, text: impl Into<String>) -> Self {
17        Reason { code: code.into(), text: text.into() }
18    }
19}
20
21#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
22pub struct Step {
23    pub id: String,
24    pub label: String,
25    /// `pending` | `ok` | `fail` | `off` | `unknown`.
26    pub state: String,
27    pub text: String,
28}
29
30impl Step {
31    pub fn new(id: &str, label: &str, state: &str, text: impl Into<String>) -> Self {
32        Step { id: id.into(), label: label.into(), state: state.into(), text: text.into() }
33    }
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
37#[serde(rename_all = "lowercase")]
38pub enum Phase {
39    Direct,
40    Off,
41    Starting,
42    Waiting,
43    Ready,
44    Failed,
45    Unsupported,
46}
47
48/// What a kind reports about itself.
49#[derive(Clone, Debug, Serialize)]
50pub struct KindStatus {
51    pub phase: Phase,
52    pub progress: Option<u8>,
53    pub reason: Option<Reason>,
54    pub retry_in: Option<u64>,
55    pub steps: Vec<Step>,
56    pub detail: serde_json::Value,
57}
58
59impl KindStatus {
60    pub fn ready(detail: serde_json::Value) -> Self {
61        KindStatus { phase: Phase::Ready, progress: None, reason: None, retry_in: None, steps: Vec::new(), detail }
62    }
63}
64
65#[derive(Clone, Debug, Serialize)]
66pub struct TransportStateView {
67    pub kind: String,
68    pub label: Option<&'static str>,
69    pub supported: Vec<Kind>,
70    pub phase: Phase,
71    pub ready: bool,
72    pub blocked: bool,
73    pub progress: Option<u8>,
74    pub reason: Option<Reason>,
75    pub retry_in: Option<u64>,
76    pub since: u64,
77    pub prelogin: String,
78    pub prelogin_armed: bool,
79    pub realtime_allowed: bool,
80    pub realtime_active: bool,
81    pub call_active: bool,
82    pub config_seq: u64,
83    pub steps: Vec<Step>,
84    pub detail: serde_json::Value,
85}
86
87pub fn not_in_build(k: Kind) -> Reason {
88    Reason::new("not_in_build", format!("This build doesn't include {}.", k.label()))
89}
90
91pub fn unknown_network() -> Reason {
92    Reason::new("unknown_network", "Choose how Vector connects.")
93}
94
95/// The status of a kind whose instance is not installed (Tor reports its bootstrap here).
96fn uninstalled_status(k: Kind) -> KindStatus {
97    if !k.compiled() {
98        return KindStatus {
99            phase: Phase::Unsupported,
100            progress: None,
101            reason: Some(not_in_build(k)),
102            retry_in: None,
103            steps: Vec::new(),
104            detail: serde_json::Value::Null,
105        };
106    }
107    match k {
108        #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
109        Kind::Tor => crate::tor::uninstalled_status(),
110        _ => KindStatus {
111            phase: Phase::Starting,
112            progress: None,
113            reason: None,
114            retry_in: None,
115            steps: Vec::new(),
116            detail: serde_json::Value::Null,
117        },
118    }
119}
120
121/// The chosen kind's status: its live instance's, or what it reports while not installed.
122pub fn kind_status(k: Kind) -> KindStatus {
123    match super::host::active() {
124        Some(a) if a.kind == k && a.owner() == crate::db::live_session_id() => a.transport().kind_status(),
125        _ => uninstalled_status(k),
126    }
127}
128
129/// Why `k` is blocked right now, when it says.
130pub fn reason_for(k: Kind) -> Option<Reason> {
131    kind_status(k).reason
132}
133
134/// Blocks no amount of waiting lifts: a network this build lacks, a start that failed and is
135/// retried only by the user, or a router that turned Vector down. A transfer that waits on one
136/// only spends its whole start budget to fail the same way.
137const NEEDS_USER: &[&str] = &["not_in_build", "tor_failed", "sam_refused", "sam_too_old", "sam_auth_required", "sam_auth_failed"];
138
139/// Whether the live account's network is held by something only the user can change.
140pub fn waits_for_user() -> bool {
141    let Some(k) = super::preference().filter(|k| *k != Kind::Clearnet) else { return false };
142    let ks = kind_status(k);
143    matches!(ks.phase, Phase::Failed | Phase::Unsupported) || ks.reason.is_some_and(|r| NEEDS_USER.contains(&r.code.as_str()))
144}
145
146fn now_secs() -> u64 {
147    crate::clock::now_secs()
148}
149
150static PHASE_SINCE: Mutex<Option<(String, Phase, u64)>> = Mutex::new(None);
151
152fn since(kind: &str, phase: Phase) -> u64 {
153    let mut slot = PHASE_SINCE.lock().unwrap_or_else(|e| e.into_inner());
154    match slot.as_ref() {
155        Some((k, p, t)) if k == kind && *p == phase => *t,
156        _ => {
157            let t = now_secs();
158            *slot = Some((kind.to_string(), phase, t));
159            t
160        }
161    }
162}
163
164fn realtime_active() -> bool {
165    #[cfg(feature = "xdc")]
166    {
167        crate::xdc::session::any_live()
168    }
169    #[cfg(not(feature = "xdc"))]
170    {
171        false
172    }
173}
174
175pub fn call_active() -> bool {
176    #[cfg(feature = "calls")]
177    {
178        crate::calls::session::snapshot().is_some()
179    }
180    #[cfg(not(feature = "calls"))]
181    {
182        false
183    }
184}
185
186pub fn view() -> TransportStateView {
187    let pref = super::preference();
188    let state = super::state();
189    let (kind, label, ks) = match pref {
190        None => (
191            "unknown".to_string(),
192            None,
193            KindStatus {
194                phase: Phase::Off,
195                progress: None,
196                reason: Some(unknown_network()),
197                retry_in: None,
198                steps: Vec::new(),
199                detail: serde_json::Value::Null,
200            },
201        ),
202        Some(Kind::Clearnet) => (
203            "clearnet".to_string(),
204            Some(Kind::Clearnet.label()),
205            KindStatus {
206                phase: Phase::Direct,
207                progress: None,
208                reason: None,
209                retry_in: None,
210                steps: Vec::new(),
211                detail: serde_json::Value::Null,
212            },
213        ),
214        Some(k) => (k.as_str().to_string(), Some(k.label()), kind_status(k)),
215    };
216    let ready = matches!(state, TransportState::Clearnet | TransportState::Active { .. });
217    let prelogin = match super::prelogin::marker_kind() {
218        Ok(Some(k)) => k.as_str().to_string(),
219        Ok(None) => "clearnet".to_string(),
220        Err(super::prelogin::UnreadableMarker) => "unknown".to_string(),
221    };
222    let phase = if ready && ks.phase != Phase::Direct { Phase::Ready } else { ks.phase };
223    TransportStateView {
224        since: since(&kind, phase),
225        kind,
226        label,
227        supported: super::supported(),
228        phase,
229        ready,
230        blocked: !ready,
231        progress: ks.progress,
232        reason: if ready { None } else { ks.reason },
233        retry_in: ks.retry_in,
234        prelogin,
235        prelogin_armed: super::prelogin::armed().is_some(),
236        realtime_allowed: super::realtime::allowed(),
237        realtime_active: realtime_active(),
238        call_active: call_active(),
239        config_seq: super::prefs::live().config_seq(),
240        steps: ks.steps,
241        detail: ks.detail,
242    }
243}
244
245#[derive(Clone, Debug, Serialize)]
246pub struct RouteView {
247    pub url: String,
248    pub host: String,
249    pub kind: String,
250    /// `direct` | `native` | `twin` | `exit` | `refused` | `blocked`.
251    pub class: String,
252    pub via: Option<String>,
253    pub text: String,
254    pub last_error: Option<String>,
255}
256
257/// How long a recorded failure still describes a host.
258const RECENT_FAILURE: std::time::Duration = std::time::Duration::from_secs(30);
259
260pub fn route_view(url: &str) -> RouteView {
261    let (host, port) = super::host_port(url).unwrap_or_default();
262    let pref = super::preference();
263    let kind = pref.map_or("unknown", Kind::as_str).to_string();
264    let mk = |class: &str, via: Option<String>, text: String, last_error: Option<String>| RouteView {
265        url: url.to_string(),
266        host: host.clone(),
267        kind: kind.clone(),
268        class: class.to_string(),
269        via,
270        text,
271        last_error,
272    };
273    let Some(dest) = super::Dest::parse(&host) else {
274        return mk("refused", None, super::Refusal::BadName.text(), None);
275    };
276    if let Some(r) = super::route::pre_route(pref.unwrap_or(Kind::Clearnet), &dest) {
277        return mk("refused", None, r.text(), None);
278    }
279    match super::state() {
280        TransportState::Clearnet => mk("direct", None, "Direct".into(), None),
281        TransportState::Unknown => {
282            let t = super::ConnectError::NotReady(None).text();
283            mk("blocked", None, format!("Blocked: {t}"), Some(t))
284        }
285        TransportState::RequiredButInactive { kind } => {
286            let t = reason_for(kind).map(|r| r.text).unwrap_or_else(|| super::ConnectError::NotReady(Some(kind)).text());
287            mk("blocked", None, format!("Blocked: {t}"), Some(t))
288        }
289        TransportState::Active { kind } => {
290            let Some(active) = super::host::active().filter(|a| a.kind == kind) else {
291                return mk("blocked", None, super::ConnectError::NotReady(Some(kind)).text(), None);
292            };
293            let p = super::prefs::live();
294            let (aliases, config) = (p.aliases(), p.config(kind));
295            let route = active.transport().route(&dest, port, &super::RouteCtx { aliases: &aliases, config: &config });
296            let last = active
297                .last_failure(&dest.host())
298                .filter(|(at, _)| at.elapsed() < RECENT_FAILURE)
299                .map(|(_, e)| e.text());
300            match &route {
301                super::Route::Refuse(r) => mk("refused", None, r.text(), last),
302                super::Route::Native { .. } => mk("native", None, format!("Inside {}", kind.label()), last),
303                super::Route::Twin { via, .. } => mk("twin", Some(via.clone()), format!("Through its {}", kind.address_noun()), last),
304                super::Route::Exit { .. } => {
305                    let via = active.last_exit(&dest.host()).map(|id| outproxy_name(&config, &id));
306                    let text = match (kind, &via) {
307                        (Kind::Tor, _) => "Through Tor".to_string(),
308                        (_, Some(name)) => format!("Through the {name} outproxy"),
309                        (_, None) => "Through an outproxy".to_string(),
310                    };
311                    mk("exit", via, text, last)
312                }
313            }
314        }
315    }
316}
317
318fn outproxy_name(config: &super::KindConfig, id: &str) -> String {
319    config
320        .downcast_ref::<super::i2p_config::I2pConfig>()
321        .and_then(|c| c.outproxy_list().into_iter().find(|o| o.id == id).map(|o| o.name))
322        .unwrap_or_else(|| id.to_string())
323}