Skip to main content

i3status_rs/blocks/
speedtest.rs

1//! Ping, jitter, download, and upload speeds
2//!
3//! This block uses Cloudflare's [networkquality-rs](https://github.com/cloudflare/networkquality-rs) (nq) library to run a speedtest and report the ping, jitter, download speed, and upload speed.
4//!
5//! The block can be configured to use custom endpoints for the speedtest, but by default Cloudflare's nq endpoints are used.
6//!
7//!  For example setting `config_url` to `"https://mensura.cdn-apple.com/.well-known/nq"` will use Apple's nq endpoints instead of Cloudflare's.
8//!
9//! nq is based on the IETF draft: ["Responsiveness under Working Conditions"](https://datatracker.ietf.org/doc/draft-ietf-ippm-responsiveness/).
10//!
11//! The draft defines "responsiveness", measured in **R**ound trips **P**er **M**inute (RPM), as a useful measurement of network quality.
12//!
13//! # Configuration
14//!
15//! Key | Values | Default
16//! ----|--------|--------
17//! `format` | A string to customise the output of this block. See below for available placeholders. | `" ^icon_ping {$ping.eng(prefix:m)\|----} ^icon_net_down {$speed_down.eng(w:3, prefix:M)ps\|-------} ^icon_net_up {$speed_up.eng(w:3, prefix:M)ps\|-------} "`
18//! `interval` | Update interval in seconds | `1800`
19//! `config_url` | The endpoint to get the responsiveness config from. See [`SpeedtestConfig::config_url`] for the expected format of the configuration JSON returned by this endpoint. | `None`
20//! `large_download_url` | The large file endpoint which should be multiple GBs. | `"https://h3.speed.cloudflare.com/__down?bytes=10000000000"`
21//! `small_download_url` | The small file endpoint which should be very small, only a few bytes. | `"https://h3.speed.cloudflare.com/__down?bytes=10"`
22//! `upload_url` | The upload url which accepts an arbitrary amount of data. | `"https://h3.speed.cloudflare.com/__up"`
23//! `latency` | Arguments for the latency test. | [See table below](#latency-configuration-settings-used-for-ping-and-jitter)
24//! `rpm` | Arguments for the RPM test. | [See table below](#rpm-configuration-settings-used-for-speed_down-and-speed_up)
25//!
26//! # Latency Configuration (settings used for `ping` and `jitter`)
27//!
28//! Key | Values | Default
29//! ----|--------|--------
30//! `runs` | The number of latency test runs to perform. | `20`
31//!
32//! # RPM Configuration (settings used for `speed_down` and `speed_up`)
33//!
34//! Key | Values | Default
35//! ----|--------|--------
36//! `moving_average_distance` | The number of intervals to use when calculating the moving average. | `4`
37//! `std_tolerance` | How far a measurement is allowed to be from the previous moving average before the measurement is considered unstable. | `0.05`
38//! `trimmed_mean_percent` | Determines which percentile to use for averaging when calculating the trimmed mean of throughputs or RPM scores. A value of `0.95` means to only use values in the 95th percentile to calculate an average. | `0.95`
39//! `max_loaded_connections` | The maximum number of loaded connections that the test can use to saturate the network. | `16`
40//! `interval_duration_ms` | The duration between test intervals in milliseconds (ms). | `500` (0.5 seconds)
41//! `test_duration_ms` | The overall test duration in milliseconds (ms). | `12_000` (12 seconds)
42//! `conn_type` | The type of connection to use for the speed test. Either `"h1"` or `"h2"` | `"h2"`
43//! `upload_bytes_per_request` | The number of bytes to upload per request during the speed test. | `100_000_000`
44//!
45//! # Available Format Keys
46//!
47//! Placeholder  | Value          | Type   | Unit
48//! -------------|----------------|--------|---------------
49//! `ping`       | Ping delay     | Number | Seconds
50//! `jitter`     | Jitter         | Number | Seconds
51//! `speed_down` | Download speed | Number | Bits per second
52//! `speed_up`   | Upload speed   | Number | Bits per second
53//!
54//! # Examples
55//!
56//! Show only ping (with an icon)
57//!
58//! ```toml
59//! [[block]]
60//! block = "speedtest"
61//! format = " ^icon_ping $ping "
62//! ```
63//!
64//! Hide ping and display speed in bytes per second each using 4 characters (without icons)
65//!
66//! ```toml
67//! [[block]]
68//! block = "speedtest"
69//! format = " $speed_down.eng(w:4,u:B) $speed_up(w:4,u:B) "
70//! ```
71//!
72//! Advanced configuration
73//!
74//! ```toml
75//! [[block]]
76//! block = "speedtest"
77//! [block.latency]
78//! runs = 5
79//! [block.rpm]
80//! conn_type = "h1"
81//! ```
82//!
83//! # Icons Used
84//! - `ping` (`^icon_ping`)
85//! - `net_down` (`^icon_net_down`)
86//! - `net_up` (`^icon_net_up`)
87
88use std::sync::Arc;
89
90use cf_mach::{
91    nq_core::{ConnectionType, Network, Time, TokioTime},
92    nq_latency::{Latency, LatencyConfig, LatencyResult},
93    nq_rpm::{ConnectionErrorPolicy, Responsiveness, ResponsivenessConfig, ResponsivenessResult},
94    nq_tokio_network::TokioNetwork,
95};
96use reqwest::Url;
97use serde::{Deserialize, Deserializer};
98use tokio_util::sync::CancellationToken;
99
100use super::prelude::*;
101
102make_log_macro!(debug, "speedtest");
103
104#[derive(Deserialize, Debug, SmartDefault)]
105#[serde(deny_unknown_fields, default)]
106pub struct Config {
107    pub format: FormatConfig,
108    #[default(1800.into())]
109    pub interval: Seconds,
110    #[serde(flatten)]
111    pub speedtest: SpeedtestConfig,
112}
113
114#[derive(Debug, Deserialize, SmartDefault)]
115#[serde(deny_unknown_fields, default)]
116pub struct SpeedtestConfig {
117    /// The endpoint to get the responsiveness config from. Should be JSON in
118    /// the form:
119    ///
120    /// ```json
121    /// {
122    ///     "version": number,
123    ///     "test_endpoint": string?,
124    ///     "urls": {
125    ///         "small_https_download_url": string,
126    ///         "large_https_download_url": string,
127    ///         "https_upload_url": string
128    ///     }
129    /// }
130    /// ```
131    #[serde(deserialize_with = "deserialize_url_opt")]
132    pub config_url: Option<Url>,
133    /// The large file endpoint which should be multiple GBs.
134    #[default("https://h3.speed.cloudflare.com/__down?bytes=10000000000".parse().unwrap())]
135    pub large_download_url: Url,
136    /// The small file endpoint which should be very small, only a few bytes.
137    #[default("https://h3.speed.cloudflare.com/__down?bytes=10".parse().unwrap())]
138    #[serde(deserialize_with = "deserialize_url")]
139    pub small_download_url: Url,
140    /// The upload url which accepts an arbitrary amount of data.
141    #[default("https://h3.speed.cloudflare.com/__up".parse().unwrap())]
142    #[serde(deserialize_with = "deserialize_url")]
143    pub upload_url: Url,
144    pub latency: LatencyConfigOpts,
145    pub rpm: RpmConfigOpts,
146}
147
148#[derive(Debug, Deserialize, SmartDefault)]
149#[serde(deny_unknown_fields, default)]
150pub struct LatencyConfigOpts {
151    /// The number of runs to perform when measuring latency.
152    #[default(20)]
153    pub runs: usize,
154}
155
156#[derive(Debug, Deserialize, SmartDefault)]
157#[serde(deny_unknown_fields, default)]
158pub struct RpmConfigOpts {
159    /// The number of intervals to use when calculating the moving average.
160    #[default(4)]
161    pub moving_average_distance: usize,
162    /// How far a measurement is allowed to be from the previous moving average
163    /// before the measurement is considered unstable.
164    #[default(0.05)]
165    pub std_tolerance: f64,
166    /// Determines which percentile to use for averaging when calculating the
167    /// trimmed mean of throughputs or RPM scores. A value of `0.95` means to
168    /// only use values in the 95th percentile to calculate an average.
169    #[default(0.95)]
170    pub trimmed_mean_percent: f64,
171    /// The maximum number of loaded connections that the test can use to
172    /// saturate the network.
173    #[default(16)]
174    pub max_loaded_connections: usize,
175    /// The duration between test intervals.
176    #[default(Duration::from_millis(500))]
177    #[serde(deserialize_with = "deserialize_duration_ms")]
178    pub interval_duration_ms: Duration,
179    /// The overall test duration.
180    #[default(Duration::from_millis(12_000))]
181    #[serde(deserialize_with = "deserialize_duration_ms")]
182    pub test_duration_ms: Duration,
183    /// Create an HTTP/1.1, HTTP/2, or HTTP/3 connection.
184    #[default(ConnectionType::H2)]
185    #[serde(deserialize_with = "deserialize_conn_type")]
186    pub conn_type: ConnectionType,
187    /// Maximum bytes sent in any single upload load-generating request.
188    ///
189    /// Upload load is generated as a sequence of requests of this size on each
190    /// connection, rather than one enormous request, because servers may cap
191    /// request body size and reject anything larger with HTTP 413. Such caps
192    /// apply per-request, so staying under one here keeps the link loaded
193    /// indefinitely without ever tripping it.
194    ///
195    /// Must be below the smallest such cap on the path, with margin. It has no
196    /// effect on connections too slow to send this many bytes within the test
197    /// duration, since their first request never completes either way.
198    #[default(100_000_000)]
199    pub upload_bytes_per_request: usize,
200}
201
202pub(crate) fn prepare(config: &Config) -> Result<Arc<BlockPlan>> {
203    // The icons (`ping`, `net_down`, `net_up`) are rendered by `^icon_*`
204    // format tokens, not icon-valued placeholders, so no icons are declared.
205    BlockPlan::new(vec![OutputPlan::new(
206        "main",
207        config.format.with_default(
208            " ^icon_ping {$ping.eng(prefix:m)|----} ^icon_net_down {$speed_down.eng(w:3, prefix:M)ps|-------} ^icon_net_up {$speed_up.eng(w:3, prefix:M)ps|-------} ",
209        )?,
210    )])
211}
212
213pub(crate) async fn run(config: &Config, api: &CommonApi, plan: &Arc<BlockPlan>) -> Result<()> {
214    let output_main = plan.output("main")?;
215
216    let mut speedtest = Speedtest::new(api, output_main);
217
218    loop {
219        speedtest.run_tests(config).await?;
220
221        select! {
222            _ = sleep(config.interval.0) => (),
223            _ = api.wait_for_update_request() => (),
224        }
225    }
226}
227
228#[derive(Debug, Deserialize)]
229struct SpeedtestUrls {
230    #[serde(alias = "small_download_url", deserialize_with = "deserialize_url")]
231    small_https_download_url: Url,
232    #[serde(alias = "large_download_url", deserialize_with = "deserialize_url")]
233    large_https_download_url: Url,
234    #[serde(alias = "upload_url", deserialize_with = "deserialize_url")]
235    https_upload_url: Url,
236}
237
238#[derive(Deserialize)]
239struct RpmServerConfig {
240    urls: SpeedtestUrls,
241}
242
243/// Get speedtest urls
244async fn get_speedtest_urls(speedtest_config: &SpeedtestConfig) -> Result<SpeedtestUrls> {
245    match speedtest_config.config_url.clone() {
246        Some(config_url) => {
247            debug!("fetching configuration from {config_url}");
248            let urls = REQWEST_CLIENT
249                .get(config_url)
250                .send()
251                .await
252                .error("Failed to send request with reqwest")?
253                .json::<RpmServerConfig>()
254                .await
255                .error("Failed to parse JSON from rpm config endpoint")?
256                .urls;
257            debug!("retrieved configuration urls: {urls:?}");
258
259            Ok(urls)
260        }
261        None => Ok(SpeedtestUrls {
262            small_https_download_url: speedtest_config.small_download_url.clone(),
263            large_https_download_url: speedtest_config.large_download_url.clone(),
264            https_upload_url: speedtest_config.upload_url.clone(),
265        }),
266    }
267}
268
269#[derive(Default)]
270struct Metrics {
271    ping: Option<f64>,
272    jitter: Option<f64>,
273    speed_down: Option<f64>,
274    speed_up: Option<f64>,
275}
276
277struct Speedtest {
278    api: CommonApi,
279    output: OutputHandle,
280    need_ping: bool,
281    need_jitter: bool,
282    need_speed_down: bool,
283    need_speed_up: bool,
284    metrics: Metrics,
285}
286
287impl Speedtest {
288    fn new(api: &CommonApi, output: OutputHandle) -> Self {
289        let format = output.format();
290
291        let need_ping = format.contains_key("ping");
292        let need_jitter = format.contains_key("jitter");
293        let need_speed_down = format.contains_key("speed_down");
294        let need_speed_up = format.contains_key("speed_up");
295
296        Self {
297            api: api.clone(),
298            output,
299            need_ping,
300            need_jitter,
301            need_speed_down,
302            need_speed_up,
303            metrics: Metrics::default(),
304        }
305    }
306
307    fn update_values(&self) -> Result<()> {
308        let mut values = HashMap::new();
309        if let Some(ping) = self.metrics.ping {
310            values.insert("ping".into(), Value::seconds(ping));
311        }
312        if let Some(jitter) = self.metrics.jitter {
313            values.insert("jitter".into(), Value::seconds(jitter));
314        }
315        if let Some(speed_down) = self.metrics.speed_down {
316            values.insert("speed_down".into(), Value::bits(speed_down));
317        }
318        if let Some(speed_up) = self.metrics.speed_up {
319            values.insert("speed_up".into(), Value::bits(speed_up));
320        }
321        let mut widget = self.output.new_widget();
322        widget.set_values(values);
323        self.api.set_widget(widget)
324    }
325
326    async fn run_tests(&mut self, config: &Config) -> Result<()> {
327        let speedtest_urls = get_speedtest_urls(&config.speedtest).await?;
328
329        // Reset metrics before running tests
330        self.metrics = Metrics::default();
331        self.update_values()?;
332
333        if self.need_ping || self.need_jitter {
334            debug!("running latency test");
335
336            let latency_results = self
337                .test_latency(LatencyConfig {
338                    url: speedtest_urls.small_https_download_url.clone(),
339                    runs: config.speedtest.latency.runs,
340                    scoped_headers: None,
341                })
342                .await?;
343
344            if self.need_ping {
345                self.metrics.ping =
346                    Some(latency_results.median().error("no median RTT available")?);
347            }
348
349            if self.need_jitter {
350                self.metrics.jitter = Some(latency_results.jitter().error("no jitter available")?);
351            }
352            self.update_values()?;
353        }
354
355        if self.need_speed_down || self.need_speed_up {
356            let responsiveness_config = ResponsivenessConfig {
357                large_download_url: speedtest_urls.large_https_download_url,
358                small_download_url: speedtest_urls.small_https_download_url,
359                upload_url: speedtest_urls.https_upload_url,
360                moving_average_distance: config.speedtest.rpm.moving_average_distance,
361                interval_duration: config.speedtest.rpm.interval_duration_ms,
362                test_duration: config.speedtest.rpm.test_duration_ms,
363                trimmed_mean_percent: config.speedtest.rpm.trimmed_mean_percent,
364                std_tolerance: config.speedtest.rpm.std_tolerance,
365                max_loaded_connections: config.speedtest.rpm.max_loaded_connections,
366                conn_type: config.speedtest.rpm.conn_type,
367                upload_bytes_per_request: config.speedtest.rpm.upload_bytes_per_request,
368                // This is false for RPM, but true for a saturation test
369                determine_load_only: false,
370                on_connection_error: ConnectionErrorPolicy::default(),
371                scoped_headers: None,
372            };
373
374            if self.need_speed_down {
375                debug!("running download test");
376                let download_result = self
377                    .test_network_speed(&responsiveness_config, true)
378                    .await?;
379                self.metrics.speed_down = Some(
380                    download_result
381                        .throughput()
382                        .error("no download throughput available")? as f64,
383                );
384                self.update_values()?;
385            }
386
387            if self.need_speed_up {
388                debug!("running upload test");
389                let upload_result = self
390                    .test_network_speed(&responsiveness_config, false)
391                    .await?;
392                self.metrics.speed_up = Some(
393                    upload_result
394                        .throughput()
395                        .error("no upload throughput available")? as f64,
396                );
397                self.update_values()?;
398            }
399        }
400        Ok(())
401    }
402
403    async fn test_latency(&self, config: LatencyConfig) -> Result<LatencyResult> {
404        let shutdown = CancellationToken::new();
405        let time: Arc<dyn Time> = Arc::new(TokioTime::new());
406        let network: Arc<dyn Network> =
407            Arc::new(TokioNetwork::new(Arc::clone(&time), shutdown.clone()));
408
409        let rtt = Latency::new(config);
410        let result = rtt
411            .run_test(network, time, shutdown.clone())
412            .await
413            .map_err(|e| Error::new(e.to_string()))?;
414
415        debug!("shutting down latency test");
416        let _ = tokio::time::timeout(tokio::time::Duration::from_secs(1), async {
417            shutdown.cancel();
418        })
419        .await;
420
421        Ok(result)
422    }
423
424    async fn test_network_speed(
425        &mut self,
426        config: &ResponsivenessConfig,
427        download: bool,
428    ) -> Result<ResponsivenessResult> {
429        let shutdown = CancellationToken::new();
430        let time: Arc<dyn Time> = Arc::new(TokioTime::new());
431        let network: Arc<dyn Network> =
432            Arc::new(TokioNetwork::new(Arc::clone(&time), shutdown.clone()));
433
434        let rpm =
435            Responsiveness::new(config.clone(), download).map_err(|e| Error::new(e.to_string()))?;
436        let mut progress = rpm.subscribe();
437        let test = rpm.run_test(network, time, shutdown.clone());
438        tokio::pin!(test);
439
440        let result = loop {
441            select! {
442                result = &mut test => break result.map_err(|e| Error::new(e.to_string()))?,
443                Ok(()) = progress.changed() => {
444                    // Moving average aggregate goodput across the load-generating
445                    // connections, in bits per second.
446                    let goodput = progress.borrow_and_update().goodput;
447                    if download{
448                        self.metrics.speed_down = Some(goodput);
449                    } else {
450                        self.metrics.speed_up = Some(goodput);
451                    }
452                    self.update_values()?;
453                }
454            }
455        };
456
457        debug!("shutting down network speed test");
458        let _ = tokio::time::timeout(tokio::time::Duration::from_secs(1), async {
459            shutdown.cancel();
460        })
461        .await;
462
463        Ok(result)
464    }
465}
466
467fn deserialize_url_opt<'de, D>(deserializer: D) -> Result<Option<Url>, D::Error>
468where
469    D: Deserializer<'de>,
470{
471    let url_opt = Option::<String>::deserialize(deserializer)?;
472    url_opt
473        .map(|url| url.parse().map_err(serde::de::Error::custom))
474        .transpose()
475}
476
477fn deserialize_url<'de, D>(deserializer: D) -> Result<Url, D::Error>
478where
479    D: Deserializer<'de>,
480{
481    let url = String::deserialize(deserializer)?;
482    url.parse().map_err(serde::de::Error::custom)
483}
484
485fn deserialize_duration_ms<'de, D>(deserializer: D) -> Result<Duration, D::Error>
486where
487    D: Deserializer<'de>,
488{
489    let duration_ms = u64::deserialize(deserializer)?;
490    Ok(Duration::from_millis(duration_ms))
491}
492
493fn deserialize_conn_type<'de, D>(deserializer: D) -> Result<ConnectionType, D::Error>
494where
495    D: Deserializer<'de>,
496{
497    let conn_type_str = String::deserialize(deserializer)?;
498    match conn_type_str.as_str() {
499        "h1" => Ok(ConnectionType::H1 { use_tls: true }),
500        "h2" => Ok(ConnectionType::H2),
501        _ => Err(serde::de::Error::custom(format!(
502            "Invalid connection type: {}. Either: \"h1\" or \"h2\"",
503            conn_type_str
504        ))),
505    }
506}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511
512    #[test]
513    fn plan_declares_main_output_without_icon_placeholders() {
514        let plan = prepare(&Config::default()).unwrap();
515        let declared: Vec<_> = plan.outputs().map(|o| o.id()).collect();
516        assert_eq!(declared, ["main"]);
517        let output = plan.output("main").unwrap();
518        // Every icon this block draws is a `^icon_*` token in the format
519        // rather than an icon value, so the icon surface is entirely static.
520        assert_eq!(output.output().icon_placeholders().count(), 0);
521        assert_eq!(
522            output.output().static_icons(),
523            ["ping", "net_down", "net_up"]
524        );
525    }
526
527    #[test]
528    fn a_format_without_icons_declares_none() {
529        let config = Config {
530            format: " $ping ".parse().unwrap(),
531            ..Config::default()
532        };
533        let plan = prepare(&config).unwrap();
534        let output = plan.output("main").unwrap();
535        assert!(output.output().static_icons().is_empty());
536    }
537
538    #[test]
539    fn custom_format_is_respected() {
540        let config = Config {
541            format: " $ping ".parse().unwrap(),
542            ..Config::default()
543        };
544        let plan = prepare(&config).unwrap();
545        let output = plan.output("main").unwrap();
546        assert!(output.format().contains_key("ping"));
547        assert!(!output.format().contains_key("speed_down"));
548    }
549}