diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs
index 66834eb7fe..34d986226b 100644
--- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs
+++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs
@@ -7718,6 +7718,15 @@ public static string LastScanAtX {
}
}
+ ///
+ /// Looks up a localized string similar to Last test at {0}.
+ ///
+ public static string LastTestAtX {
+ get {
+ return ResourceManager.GetString("LastTestAtX", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Last usable IP address.
///
@@ -16668,6 +16677,15 @@ public static string XPoweredBy {
}
}
+ ///
+ /// Looks up a localized string similar to {0} requests failed and were skipped. The result may be less accurate..
+ ///
+ public static string XRequestsFailedAndWereSkippedMessage {
+ get {
+ return ResourceManager.GetString("XRequestsFailedAndWereSkippedMessage", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to {0} Timed out.
///
@@ -16713,6 +16731,15 @@ public static string XXXDetectedAsLocalIPAddressMessage {
}
}
+ ///
+ /// Looks up a localized string similar to {0} did not respond within {1} seconds..
+ ///
+ public static string XXXDidNotRespondWithinXXXSecondsMessage {
+ get {
+ return ResourceManager.GetString("XXXDidNotRespondWithinXXXSecondsMessage", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to {0} disconnected!.
///
diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx
index 632c9159d6..4f716f4d67 100644
--- a/Source/NETworkManager.Localization/Resources/Strings.resx
+++ b/Source/NETworkManager.Localization/Resources/Strings.resx
@@ -5758,4 +5758,13 @@ Do you want to start the scan?
All widgets are hidden. You can show them in the settings of the dashboard.
+
+ {0} did not respond within {1} seconds.
+
+
+ {0} requests failed and were skipped. The result may be less accurate.
+
+
+ Last test at {0}
+
\ No newline at end of file
diff --git a/Source/NETworkManager.Models/Cloudflare/SpeedTestCalculator.cs b/Source/NETworkManager.Models/Cloudflare/SpeedTestCalculator.cs
new file mode 100644
index 0000000000..c41d5b41b3
--- /dev/null
+++ b/Source/NETworkManager.Models/Cloudflare/SpeedTestCalculator.cs
@@ -0,0 +1,173 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net.Http;
+using System.Text.RegularExpressions;
+
+namespace NETworkManager.Models.Cloudflare;
+
+///
+/// Calculations of the speed test, like the official
+/// cloudflare/speedtest library.
+///
+public static class SpeedTestCalculator
+{
+ ///
+ /// Server time of the request, e.g. cfRequestDuration;dur=12.3.
+ ///
+ private static readonly Regex RequestDurationRegex = new(@"(?:^|,\s*)cfReq(?:uest)?Dur(?:ation)?;\s*dur=([0-9.]+)",
+ RegexOptions.Compiled | RegexOptions.IgnoreCase);
+
+ ///
+ /// Parts of the server time (summed up if there is no request duration), e.g. cfSpeedXyz;dur=1.2.
+ ///
+ private static readonly Regex SpeedDurationRegex = new(@"(?:^|,\s*)cfSpeed[a-zA-Z]*;\s*dur=([0-9.]+)",
+ RegexOptions.Compiled | RegexOptions.IgnoreCase);
+
+ ///
+ /// Server times up to this value (ms) are ignored.
+ ///
+ private const double ServerTimeMinDuration = 0.01;
+
+ ///
+ /// Longest delay before a request that failed with HTTP 429 is repeated.
+ ///
+ private static readonly TimeSpan MaxRetryDelay = TimeSpan.FromSeconds(60);
+
+ ///
+ /// Percentile of the values with linear interpolation between the two closest ranks.
+ ///
+ /// Values (unsorted).
+ /// Percentile between 0 and 1 (e.g. 0.9).
+ /// Percentile, 0 if there are no values.
+ public static double Percentile(IReadOnlyCollection values, double p)
+ {
+ if (values == null || values.Count == 0)
+ return 0.0;
+
+ var sorted = values.OrderBy(v => v).ToList();
+
+ if (sorted.Count == 1)
+ return sorted[0];
+
+ var rank = p * (sorted.Count - 1);
+ var lower = (int)Math.Floor(rank);
+ var upper = (int)Math.Ceiling(rank);
+
+ if (lower == upper)
+ return sorted[lower];
+
+ var weight = rank - lower;
+
+ return sorted[lower] * (1 - weight) + sorted[upper] * weight;
+ }
+
+ ///
+ /// Bandwidth shown while the test runs: the 90th percentile of the completed requests (like the result). Before the
+ /// first request has completed, the throughput of the running request.
+ ///
+ /// Bandwidth of the completed requests (bit/s).
+ /// Throughput of the running request (bit/s), null if none.
+ /// Bandwidth in bit/s, null if there is no value yet.
+ public static double? CurrentBandwidth(IReadOnlyCollection samplesBps, double? liveBps)
+ {
+ return samplesBps.Count > 0 ? Percentile(samplesBps, 0.9) : liveBps;
+ }
+
+ ///
+ /// A direction (download / upload) is finished when even the fastest request of a set took longer than the finish
+ /// duration: the larger sets would take too long (bandwidthFinishRequestDuration of the official library).
+ ///
+ /// Duration of the requests of the set (ms).
+ /// Finish duration (ms).
+ /// true if the larger sets of the direction are skipped.
+ public static bool IsDirectionFinished(IReadOnlyCollection durationsMs, double finishRequestDurationMs)
+ {
+ return durationsMs.Count > 0 && durationsMs.Min() > finishRequestDurationMs;
+ }
+
+ ///
+ /// Delay before a request that failed with HTTP 429 is repeated, from the Retry-After header (like
+ /// getRetryDelay of the official library).
+ ///
+ /// Delay of the header (seconds).
+ /// Date of the header.
+ /// Current time.
+ /// Delay, 5 seconds without a header, at most 60 seconds (the test should not wait endlessly).
+ public static TimeSpan GetRetryDelay(TimeSpan? delta, DateTimeOffset? date, DateTimeOffset now)
+ {
+ var delay = delta ?? (date.HasValue ? date.Value - now : TimeSpan.FromSeconds(5));
+
+ if (delay < TimeSpan.Zero)
+ return TimeSpan.Zero;
+
+ return delay > MaxRetryDelay ? MaxRetryDelay : delay;
+ }
+
+ ///
+ /// A request failed without a connection to the server (no response, connection lost, timeout), not because the
+ /// server or a proxy rejected it with an HTTP error.
+ ///
+ /// Error of the request.
+ /// true if there was no response.
+ public static bool IsConnectionFailure(Exception ex)
+ {
+ return ex is not HttpRequestException { StatusCode: not null };
+ }
+
+ ///
+ /// Jitter: average absolute difference between consecutive latency samples.
+ ///
+ /// Latency samples in the order they were measured.
+ /// Jitter, 0 if there are fewer than two samples.
+ public static double Jitter(IReadOnlyList pings)
+ {
+ if (pings == null || pings.Count < 2)
+ return 0.0;
+
+ double sum = 0;
+
+ for (var i = 1; i < pings.Count; i++)
+ sum += Math.Abs(pings[i] - pings[i - 1]);
+
+ return sum / (pings.Count - 1);
+ }
+
+ ///
+ /// Time the server needed to process the request, from the server-timing header: the request duration
+ /// (cfRequestDuration), otherwise the sum of the cfSpeed* durations (like cfGetServerTime of the
+ /// official library).
+ ///
+ /// Values of the server-timing header.
+ /// Server time in milliseconds, null if the header has no server time.
+ public static double? ParseServerTiming(IEnumerable values)
+ {
+ if (values == null)
+ return null;
+
+ var header = string.Join(", ", values);
+
+ if (header.Length == 0)
+ return null;
+
+ var match = RequestDurationRegex.Match(header);
+
+ if (match.Success && TryParseDuration(match, out var requestDuration) &&
+ requestDuration > ServerTimeMinDuration)
+ return requestDuration;
+
+ double sum = 0;
+
+ foreach (Match speedMatch in SpeedDurationRegex.Matches(header))
+ {
+ if (TryParseDuration(speedMatch, out var duration))
+ sum += duration;
+ }
+
+ return sum > ServerTimeMinDuration ? sum : null;
+ }
+
+ private static bool TryParseDuration(Match match, out double duration) =>
+ double.TryParse(match.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out duration);
+}
diff --git a/Source/NETworkManager.Models/Cloudflare/SpeedTestMetaInfo.cs b/Source/NETworkManager.Models/Cloudflare/SpeedTestMetaInfo.cs
index 36faa18d8a..f7310b3af5 100644
--- a/Source/NETworkManager.Models/Cloudflare/SpeedTestMetaInfo.cs
+++ b/Source/NETworkManager.Models/Cloudflare/SpeedTestMetaInfo.cs
@@ -45,7 +45,7 @@ public class SpeedTestMetaInfo
/// Autonomous System Number of the client's ISP.
///
[JsonProperty("asn")]
- public int Asn { get; set; }
+ public int? Asn { get; set; }
///
/// Human-readable ISP name (e.g. "innogy TelNet").
diff --git a/Source/NETworkManager.Models/Cloudflare/SpeedTestResult.cs b/Source/NETworkManager.Models/Cloudflare/SpeedTestResult.cs
index e584eba9e4..3273e2d5d2 100644
--- a/Source/NETworkManager.Models/Cloudflare/SpeedTestResult.cs
+++ b/Source/NETworkManager.Models/Cloudflare/SpeedTestResult.cs
@@ -1,3 +1,5 @@
+using System.Linq;
+
namespace NETworkManager.Models.Cloudflare;
///
@@ -34,16 +36,6 @@ public class SpeedTestResult
///
public string Isp { get; set; }
- ///
- /// City of the client (Cloudflare meta city).
- ///
- public string ClientCity { get; set; }
-
- ///
- /// ISO 3166-1 alpha-2 country code of the client (Cloudflare meta country).
- ///
- public string ClientCountry { get; set; }
-
///
/// City of the Cloudflare PoP serving the test, e.g. "Frankfurt-am-Main".
///
@@ -60,12 +52,24 @@ public class SpeedTestResult
public string ServerIata { get; set; }
///
- /// Indicates that the speed test run failed.
+ /// Cloudflare server for the UI, e.g. "Frankfurt-am-Main, DE (FRA)". null if unknown.
///
- public bool HasError { get; set; }
+ public string Server
+ {
+ get
+ {
+ var location = string.Join(", ",
+ new[] { ServerCity, ServerCountry }.Where(x => !string.IsNullOrWhiteSpace(x)));
+
+ if (string.IsNullOrWhiteSpace(ServerIata))
+ return location.Length > 0 ? location : null;
+
+ return location.Length > 0 ? $"{location} ({ServerIata})" : ServerIata;
+ }
+ }
///
- /// Error message when is true.
+ /// Number of requests that failed and were skipped (e.g. a short interruption of the connection).
///
- public string ErrorMessage { get; set; }
+ public int FailedRequests { get; set; }
}
diff --git a/Source/NETworkManager.Models/Cloudflare/SpeedTestService.cs b/Source/NETworkManager.Models/Cloudflare/SpeedTestService.cs
index 1c5b097be3..9af49bd6a3 100644
--- a/Source/NETworkManager.Models/Cloudflare/SpeedTestService.cs
+++ b/Source/NETworkManager.Models/Cloudflare/SpeedTestService.cs
@@ -6,9 +6,9 @@
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
-using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
+using log4net;
using Newtonsoft.Json;
namespace NETworkManager.Models.Cloudflare;
@@ -21,45 +21,99 @@ namespace NETworkManager.Models.Cloudflare;
///
public class SpeedTestService
{
- private const string BaseUrl = "https://speed.cloudflare.com";
+ private static readonly ILog Log = LogManager.GetLogger(typeof(SpeedTestService));
+
+ ///
+ /// Host of the speed test.
+ ///
+ public const string Host = "speed.cloudflare.com";
+
+ private const string BaseUrl = "https://" + Host;
private const string Origin = "https://speed.cloudflare.com";
- private const double DefaultEstimatedServerTimeMs = 10.0;
+ ///
+ /// Server time if the response has no server-timing header (estimatedServerTime of the official library).
+ ///
+ private const double DefaultEstimatedServerTimeMs = 0.0;
private const double BandwidthFinishRequestDurationMs = 1000.0;
private const double BandwidthMinRequestDurationMs = 10.0;
+ ///
+ /// Bytes on the wire per payload byte (HTTP headers), like the official library.
+ ///
private const double EstimatedHeaderFraction = 1.005;
+ ///
+ /// A request fails if nothing happens for this time (no response, no data received or sent). Not a limit of the
+ /// whole request: a large download / upload on a slow connection takes longer.
+ ///
+ public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(15);
+
+ ///
+ /// A request that fails with HTTP 429 (too many requests) is repeated up to this number of times after the delay of
+ /// the server (Retry-After), like the official library.
+ ///
+ private const int MaxRetries = 3;
+
+ ///
+ /// A failed request is skipped and the test continues (like the official library). After this number of requests in
+ /// a row without a connection (no response, e.g. the connection is lost), the test ends with the error. Requests
+ /// rejected by the server / a proxy (HTTP error) don't count: the connection works.
+ ///
+ private const int MaxConsecutiveFailedRequests = 3;
+
///
/// Minimum gap between mid-stream live throughput emissions, in ms.
///
private const double LiveProgressIntervalMs = 250.0;
- private static readonly Regex ServerTimingRegex = new(@"(?:^|;)\s*dur=([0-9.]+)", RegexOptions.Compiled);
+ private enum MeasurementType
+ {
+ Latency,
+ Download,
+ Upload
+ }
- private enum StepDirection { Download, Upload }
+ ///
+ /// A set of requests of the same type and size.
+ ///
+ /// Latency probes (empty download), download or upload.
+ /// Number of requests.
+ /// Size of the download / upload.
+ /// The set doesn't decide whether the direction is finished.
+ private record Measurement(MeasurementType Type, int Count, int Bytes = 0, bool BypassMinDuration = false);
///
- /// Interleaved download/upload sequence from defaultConfig.js of the
- /// official cloudflare/speedtest library. The initial 100 KB download
- /// (bypassMinDuration) is executed separately between the two latency phases.
+ /// Measurements of defaultConfig of the official cloudflare/speedtest library, in this order. A direction
+ /// (download / upload) is finished after a set whose fastest request took longer than
+ /// : its larger sets are skipped, the latency probes run anyway.
///
- private static readonly (StepDirection Direction, int Bytes, int Count)[] Steps =
- {
- (StepDirection.Download, 100_000, 9),
- (StepDirection.Download, 1_000_000, 8),
- (StepDirection.Upload, 100_000, 8),
- (StepDirection.Upload, 1_000_000, 6),
- (StepDirection.Download, 10_000_000, 6),
- (StepDirection.Upload, 10_000_000, 4),
- (StepDirection.Download, 25_000_000, 4),
- (StepDirection.Upload, 25_000_000, 4),
- (StepDirection.Download, 100_000_000, 3),
- (StepDirection.Upload, 50_000_000, 3),
- (StepDirection.Download, 250_000_000, 2),
- };
-
- private const int LatencyInitialProbes = 1;
- private const int LatencyMeasurementProbes = 20;
+ private static readonly Measurement[] Measurements =
+ [
+ new(MeasurementType.Latency, 2),
+ new(MeasurementType.Download, 1, 100_000, BypassMinDuration: true),
+ new(MeasurementType.Latency, 20),
+ new(MeasurementType.Download, 9, 100_000),
+ new(MeasurementType.Latency, 2),
+ new(MeasurementType.Download, 8, 1_000_000),
+ new(MeasurementType.Latency, 2),
+ new(MeasurementType.Upload, 8, 100_000),
+ new(MeasurementType.Latency, 2),
+ new(MeasurementType.Upload, 6, 1_000_000),
+ new(MeasurementType.Latency, 2),
+ new(MeasurementType.Download, 6, 10_000_000),
+ new(MeasurementType.Latency, 2),
+ new(MeasurementType.Upload, 4, 10_000_000),
+ new(MeasurementType.Latency, 2),
+ new(MeasurementType.Download, 4, 25_000_000),
+ new(MeasurementType.Latency, 2),
+ new(MeasurementType.Upload, 4, 25_000_000),
+ new(MeasurementType.Latency, 2),
+ new(MeasurementType.Download, 3, 100_000_000),
+ new(MeasurementType.Latency, 2),
+ new(MeasurementType.Upload, 3, 50_000_000),
+ new(MeasurementType.Latency, 2),
+ new(MeasurementType.Download, 2, 250_000_000)
+ ];
private static readonly HttpClient _client = CreateClient();
@@ -84,156 +138,145 @@ public async Task RunAsync(IProgress progres
var uploadBps = new List();
// 1. Metadata
- Emit(progress, SpeedTestPhase.FetchingMetadata, pings, downloadBps, uploadBps, null, null);
+ Emit(progress, SpeedTestPhase.FetchingMetadata, pings, downloadBps, uploadBps, null);
var meta = await FetchMetaAsync(cancellationToken).ConfigureAwait(false);
progress?.Report(new SpeedTestProgress(SpeedTestPhase.FetchingMetadata, Meta: meta));
- // 2. Initial latency probe (server-time estimation)
- Emit(progress, SpeedTestPhase.MeasuringLatency, pings, downloadBps, uploadBps, null, null);
- for (var i = 0; i < LatencyInitialProbes; i++)
- {
- await MeasureLatencyAsync(pings, cancellationToken).ConfigureAwait(false);
- Emit(progress, SpeedTestPhase.MeasuringLatency, pings, downloadBps, uploadBps, null, null);
- }
+ // 2. Latency, download and upload (official cloudflare/speedtest sequence)
+ var failures = new RequestFailures();
+ var finished = new HashSet();
+
+ // Duration of all requests per direction and size, decides whether a direction is finished
+ var durations = new Dictionary<(MeasurementType, int), List>();
- // 3. Initial download estimate (100 KB × 1 — bypassMinDuration, between the two latency phases)
- Emit(progress, SpeedTestPhase.MeasuringDownload, pings, downloadBps, uploadBps, null, null);
+ // The latency probes between the download / upload sets are short: keep showing the download / upload
+ var bandwidthStarted = false;
+ var currentPhase = SpeedTestPhase.FetchingMetadata;
+
+ foreach (var measurement in Measurements)
{
- var (bps, durationMs) = await MeasureDownloadAsync(100_000, cancellationToken,
- liveBps => Emit(progress, SpeedTestPhase.MeasuringDownload,
- pings, downloadBps, uploadBps, liveBps, null)).ConfigureAwait(false);
- if (durationMs >= BandwidthMinRequestDurationMs)
+ if (measurement.Type != MeasurementType.Latency && finished.Contains(measurement.Type))
+ continue;
+
+ if (measurement.Type != MeasurementType.Latency && !measurement.BypassMinDuration)
+ bandwidthStarted = true;
+
+ var phase = measurement.Type switch
+ {
+ MeasurementType.Download => SpeedTestPhase.MeasuringDownload,
+ MeasurementType.Upload => SpeedTestPhase.MeasuringUpload,
+ _ => bandwidthStarted ? currentPhase : SpeedTestPhase.MeasuringLatency
+ };
+
+ if (phase != currentPhase)
{
- downloadBps.Add(bps);
- Emit(progress, SpeedTestPhase.MeasuringDownload,
- pings, downloadBps, uploadBps, null, null,
- newDownloadSampleBps: bps);
+ currentPhase = phase;
+ Emit(progress, currentPhase, pings, downloadBps, uploadBps, null);
}
- }
- // 4. Proper unloaded latency measurement (20 probes)
- Emit(progress, SpeedTestPhase.MeasuringLatency, pings, downloadBps, uploadBps, null, null);
- for (var i = 0; i < LatencyMeasurementProbes; i++)
- {
- await MeasureLatencyAsync(pings, cancellationToken).ConfigureAwait(false);
- Emit(progress, SpeedTestPhase.MeasuringLatency, pings, downloadBps, uploadBps, null, null);
- }
-
- // 5. Interleaved download / upload (official cloudflare/speedtest sequence)
- var downloadStopped = false;
- var uploadStopped = false;
- var currentPhase = SpeedTestPhase.MeasuringDownload;
- Emit(progress, currentPhase, pings, downloadBps, uploadBps, null, null);
+ if (measurement.Type == MeasurementType.Latency)
+ {
+ for (var i = 0; i < measurement.Count; i++)
+ {
+ await TryRequestAsync(() => MeasureLatencyAsync(pings, cancellationToken), failures,
+ cancellationToken).ConfigureAwait(false);
+ Emit(progress, currentPhase, pings, downloadBps, uploadBps, null);
+ }
- foreach (var step in Steps)
- {
- if (step.Direction == StepDirection.Download && downloadStopped) continue;
- if (step.Direction == StepDirection.Upload && uploadStopped) continue;
+ continue;
+ }
+
+ var isDownload = measurement.Type == MeasurementType.Download;
- var stepPhase = step.Direction == StepDirection.Download
- ? SpeedTestPhase.MeasuringDownload
- : SpeedTestPhase.MeasuringUpload;
- if (stepPhase != currentPhase)
+ if (!durations.TryGetValue((measurement.Type, measurement.Bytes), out var setDurations))
{
- currentPhase = stepPhase;
- Emit(progress, currentPhase, pings, downloadBps, uploadBps, null, null);
+ setDurations = [];
+ durations[(measurement.Type, measurement.Bytes)] = setDurations;
}
- for (var i = 0; i < step.Count; i++)
+ var setSucceeded = false;
+
+ for (var i = 0; i < measurement.Count; i++)
{
- if (step.Direction == StepDirection.Download)
- {
+ var (success, (bps, durationMs)) = await TryRequestAsync(() => isDownload
+ ? MeasureDownloadAsync(measurement.Bytes, cancellationToken,
+ liveBps => Emit(progress, SpeedTestPhase.MeasuringDownload,
+ pings, downloadBps, uploadBps, liveBps))
+ : MeasureUploadAsync(measurement.Bytes, cancellationToken), failures, cancellationToken)
+ .ConfigureAwait(false);
- var phaseSnapshot = currentPhase;
- var (bps, durationMs) = await MeasureDownloadAsync(step.Bytes, cancellationToken,
- liveBps => Emit(progress, phaseSnapshot,
- pings, downloadBps, uploadBps, liveBps, null)).ConfigureAwait(false);
- if (durationMs >= BandwidthMinRequestDurationMs)
- {
- downloadBps.Add(bps);
- Emit(progress, currentPhase,
- pings, downloadBps, uploadBps, null, null,
- newDownloadSampleBps: bps);
- }
- if (durationMs >= BandwidthFinishRequestDurationMs)
- {
- downloadStopped = true;
- break;
- }
+ if (!success)
+ continue;
+
+ setSucceeded = true;
+
+ // Requests without a speed are discarded (like the official library)
+ if (bps <= 0 || double.IsInfinity(bps))
+ continue;
+
+ setDurations.Add(durationMs);
+
+ // Very short requests are too inaccurate for the result
+ if (durationMs < BandwidthMinRequestDurationMs)
+ continue;
+
+ if (isDownload)
+ {
+ downloadBps.Add(bps);
+ Emit(progress, currentPhase, pings, downloadBps, uploadBps, null,
+ newDownloadSampleBps: bps);
}
else
{
- var (bps, durationMs) = await MeasureUploadAsync(step.Bytes, cancellationToken)
- .ConfigureAwait(false);
- if (durationMs >= BandwidthMinRequestDurationMs)
- {
- uploadBps.Add(bps);
- Emit(progress, currentPhase,
- pings, downloadBps, uploadBps, null, null,
- newUploadSampleBps: bps);
- }
- if (durationMs >= BandwidthFinishRequestDurationMs)
- {
- uploadStopped = true;
- break;
- }
+ uploadBps.Add(bps);
+ Emit(progress, currentPhase, pings, downloadBps, uploadBps, null,
+ newUploadSampleBps: bps);
}
}
+
+ if (measurement.BypassMinDuration)
+ continue;
+
+ // All requests of the set failed (e.g. a proxy rejects uploads of this size): the larger sizes would fail too
+ if (!setSucceeded ||
+ SpeedTestCalculator.IsDirectionFinished(setDurations, BandwidthFinishRequestDurationMs))
+ finished.Add(measurement.Type);
}
- // 6. Result
+ // 3. Result
return new SpeedTestResult
{
- DownloadMbps = downloadBps.Count > 0 ? Percentile(downloadBps, 0.9) / 1_000_000.0 : null,
- UploadMbps = uploadBps.Count > 0 ? Percentile(uploadBps, 0.9) / 1_000_000.0 : null,
- LatencyMs = pings.Count > 0 ? Percentile(pings, 0.5) : null,
- JitterMs = pings.Count >= 2 ? Jitter(pings) : null,
+ DownloadMbps = downloadBps.Count > 0 ? SpeedTestCalculator.Percentile(downloadBps, 0.9) / 1_000_000.0 : null,
+ UploadMbps = uploadBps.Count > 0 ? SpeedTestCalculator.Percentile(uploadBps, 0.9) / 1_000_000.0 : null,
+ LatencyMs = pings.Count > 0 ? SpeedTestCalculator.Percentile(pings, 0.5) : null,
+ JitterMs = pings.Count >= 2 ? SpeedTestCalculator.Jitter(pings) : null,
Isp = meta?.AsOrganization,
- ClientCity = meta?.City,
- ClientCountry = meta?.Country,
ServerCity = meta?.Colo?.City,
ServerCountry = meta?.Colo?.Cca2,
- ServerIata = meta?.Colo?.Iata
+ ServerIata = meta?.Colo?.Iata,
+ FailedRequests = failures.Total
};
}
///
/// Builds and emits a using current
- /// sample lists. and
- /// let mid-stream callers
- /// report an instantaneous estimate even before the first completed
- /// sample is in the list.
+ /// sample lists. lets the running
+ /// download report an instantaneous estimate before the first completed
+ /// sample is in the list (uploads only report completed samples).
///
private static void Emit(IProgress progress, SpeedTestPhase phase,
List pings, List downloadBps, List uploadBps,
- double? liveDownloadBpsOverride, double? liveUploadBpsOverride,
+ double? liveDownloadBpsOverride,
double? newDownloadSampleBps = null, double? newUploadSampleBps = null)
{
if (progress == null)
return;
- // P90 of completed samples ⊔ current live instantaneous — consistent with
- // the final result formula; live override applies only before the first sample.
- double? downloadMbps = null;
- if (downloadBps.Count > 0 || liveDownloadBpsOverride.HasValue)
- {
- var p90Bps = downloadBps.Count > 0 ? Percentile(downloadBps, 0.9) : 0.0;
- if (liveDownloadBpsOverride.HasValue && liveDownloadBpsOverride.Value > p90Bps)
- p90Bps = liveDownloadBpsOverride.Value;
- downloadMbps = p90Bps / 1_000_000.0;
- }
-
- double? uploadMbps = null;
- if (uploadBps.Count > 0 || liveUploadBpsOverride.HasValue)
- {
- var p90Bps = uploadBps.Count > 0 ? Percentile(uploadBps, 0.9) : 0.0;
- if (liveUploadBpsOverride.HasValue && liveUploadBpsOverride.Value > p90Bps)
- p90Bps = liveUploadBpsOverride.Value;
- uploadMbps = p90Bps / 1_000_000.0;
- }
+ var downloadMbps = SpeedTestCalculator.CurrentBandwidth(downloadBps, liveDownloadBpsOverride) / 1_000_000.0;
+ var uploadMbps = SpeedTestCalculator.CurrentBandwidth(uploadBps, null) / 1_000_000.0;
- double? latencyMs = pings.Count > 0 ? Percentile(pings, 0.5) : null;
- double? jitterMs = pings.Count >= 2 ? Jitter(pings) : null;
+ double? latencyMs = pings.Count > 0 ? SpeedTestCalculator.Percentile(pings, 0.5) : null;
+ double? jitterMs = pings.Count >= 2 ? SpeedTestCalculator.Jitter(pings) : null;
var newDownloadSampleMbps = newDownloadSampleBps / 1_000_000.0;
var newUploadSampleMbps = newUploadSampleBps / 1_000_000.0;
@@ -244,156 +287,232 @@ private static void Emit(IProgress progress, SpeedTestPhase p
#region Measurement primitives
+ private static double? ParseServerTiming(HttpResponseHeaders headers) =>
+ headers.TryGetValues("server-timing", out var values) ? SpeedTestCalculator.ParseServerTiming(values) : null;
+
+ ///
+ /// Requests the ISP and the Cloudflare server. Optional: an error is logged and the test continues without them.
+ ///
+ /// Metadata, null if the request failed.
private async Task FetchMetaAsync(CancellationToken cancellationToken)
{
- using var response = await _client.GetAsync($"{BaseUrl}/meta", cancellationToken)
- .ConfigureAwait(false);
- response.EnsureSuccessStatusCode();
- var json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
- return JsonConvert.DeserializeObject(json);
+ try
+ {
+ return await WithTimeoutAsync(async timeout =>
+ {
+ using var response = await _client.GetAsync($"{BaseUrl}/meta", timeout.Token)
+ .ConfigureAwait(false);
+ EnsureSuccess(response);
+ var json = await response.Content.ReadAsStringAsync(timeout.Token).ConfigureAwait(false);
+ return JsonConvert.DeserializeObject(json);
+ }, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ Log.Warn("Speed test metadata could not be requested.", ex);
+ return null;
+ }
}
- private async Task MeasureLatencyAsync(List pings, CancellationToken cancellationToken)
+ ///
+ /// Runs a request that fails with a if nothing happens for
+ /// . The request restarts the timeout (CancelAfter) whenever data is received or
+ /// sent.
+ ///
+ private static async Task WithTimeoutAsync(Func> request,
+ CancellationToken cancellationToken)
{
- var sw = Stopwatch.StartNew();
- using var request = new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/__down?bytes=0");
- using var response = await _client
- .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
- .ConfigureAwait(false);
- sw.Stop();
- var ttfb = sw.Elapsed.TotalMilliseconds;
- response.EnsureSuccessStatusCode();
- await response.Content.CopyToAsync(Stream.Null, cancellationToken).ConfigureAwait(false);
-
- var serverTime = ParseServerTiming(response) ?? DefaultEstimatedServerTimeMs;
- var ping = ttfb - serverTime;
- if (ping < 0) ping = 0;
- pings.Add(ping);
- }
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeout.CancelAfter(RequestTimeout);
- private async Task<(double Bps, double DurationMs)> MeasureDownloadAsync(int bytes,
- CancellationToken cancellationToken, Action onLiveBps)
- {
- var sw1 = Stopwatch.StartNew();
- using var request = new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/__down?bytes={bytes}");
- using var response = await _client
- .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
- .ConfigureAwait(false);
- sw1.Stop();
- var ttfb = sw1.Elapsed.TotalMilliseconds;
- response.EnsureSuccessStatusCode();
- var serverTime = ParseServerTiming(response) ?? DefaultEstimatedServerTimeMs;
- var ping = ttfb - serverTime;
- if (ping < 0) ping = 0;
-
- var sw2 = Stopwatch.StartNew();
- long bodyBytes;
- double lastProgressMs = 0;
- long lastProgressBytes = 0;
- await using (var stream = await response.Content
- .ReadAsStreamAsync(cancellationToken).ConfigureAwait(false))
+ try
{
- var buffer = new byte[81920];
- long total = 0;
- int read;
- while ((read = await stream.ReadAsync(buffer, cancellationToken)
- .ConfigureAwait(false)) > 0)
- {
- total += read;
- var elapsedMs = sw2.Elapsed.TotalMilliseconds;
- if (onLiveBps != null && elapsedMs - lastProgressMs >= LiveProgressIntervalMs
- && elapsedMs > 0)
- {
- // Instantaneous throughput over the last interval (delta-based)
- var deltaBytes = total - lastProgressBytes;
- var deltaMs = elapsedMs - lastProgressMs;
- var liveBps = 8.0 * deltaBytes / (deltaMs / 1000.0);
- onLiveBps(liveBps);
- lastProgressMs = elapsedMs;
- lastProgressBytes = total;
- }
- }
- bodyBytes = total;
+ return await request(timeout).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ throw new TimeoutException(
+ $"No response from {BaseUrl} within {RequestTimeout.TotalSeconds} seconds.");
}
- sw2.Stop();
- var bodyMs = sw2.Elapsed.TotalMilliseconds;
- var contentLength = response.Content.Headers.ContentLength ?? bodyBytes;
+ }
- var downloadDurationMs = ping + bodyMs;
- if (downloadDurationMs <= 0)
- return (0.0, downloadDurationMs);
+ ///
+ /// Failed requests of a test.
+ ///
+ private sealed class RequestFailures
+ {
+ public int Total { get; set; }
+ public int Consecutive { get; set; }
+ }
- var bps = 8.0 * contentLength / (downloadDurationMs / 1000.0);
- return (bps, downloadDurationMs);
+ ///
+ /// The server asks to repeat the request later (HTTP 429).
+ ///
+ private sealed class TooManyRequestsException(TimeSpan retryAfter)
+ : HttpRequestException("Too many requests.", null, HttpStatusCode.TooManyRequests)
+ {
+ public TimeSpan RetryAfter { get; } = retryAfter;
}
- private async Task<(double Bps, double DurationMs)> MeasureUploadAsync(int bytes,
- CancellationToken cancellationToken)
+ private static void EnsureSuccess(HttpResponseMessage response)
{
- using var request = new HttpRequestMessage(HttpMethod.Post, $"{BaseUrl}/__up");
- using var content = new ZeroStreamContent(bytes);
- request.Content = content;
-
- var sw = Stopwatch.StartNew();
- using var response = await _client
- .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
- .ConfigureAwait(false);
- sw.Stop();
- var ttfb = sw.Elapsed.TotalMilliseconds;
+ if (response.StatusCode == HttpStatusCode.TooManyRequests)
+ throw new TooManyRequestsException(SpeedTestCalculator.GetRetryDelay(response.Headers.RetryAfter?.Delta,
+ response.Headers.RetryAfter?.Date, DateTimeOffset.UtcNow));
+
response.EnsureSuccessStatusCode();
- await response.Content.CopyToAsync(Stream.Null, cancellationToken).ConfigureAwait(false);
+ }
- var uploadDurationMs = ttfb;
- if (uploadDurationMs <= 0)
- return (0.0, uploadDurationMs);
+ ///
+ /// Runs a request of the test like the official library: HTTP 429 is repeated after the delay of the server (up to
+ /// times), another error skips the request. After
+ /// failed requests in a row the error is thrown (the test ends).
+ ///
+ /// false if the request failed and was skipped.
+ private static async Task<(bool Success, T Value)> TryRequestAsync(Func> request,
+ RequestFailures failures, CancellationToken cancellationToken)
+ {
+ for (var retry = 0;; retry++)
+ {
+ try
+ {
+ var value = await request().ConfigureAwait(false);
+ failures.Consecutive = 0;
- var bps = 8.0 * bytes * EstimatedHeaderFraction / (uploadDurationMs / 1000.0);
- return (bps, uploadDurationMs);
- }
+ return (true, value);
+ }
+ catch (TooManyRequestsException ex) when (retry < MaxRetries)
+ {
+ Log.Warn($"Speed test request rate limited (HTTP 429), retry in {ex.RetryAfter.TotalSeconds} s.");
+ await Task.Delay(ex.RetryAfter, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is HttpRequestException or IOException or TimeoutException)
+ {
+ // Canceled by the user while data was transferred: the transport may report it as an IOException
+ cancellationToken.ThrowIfCancellationRequested();
- #endregion
+ failures.Total++;
+
+ if (!SpeedTestCalculator.IsConnectionFailure(ex))
+ failures.Consecutive = 0;
+ else if (++failures.Consecutive >= MaxConsecutiveFailedRequests)
+ throw;
- #region Helpers
+ Log.Warn("Speed test request failed and is skipped.", ex);
+
+ return (false, default);
+ }
+ }
+ }
- private static double? ParseServerTiming(HttpResponseMessage response)
+ private Task MeasureLatencyAsync(List pings, CancellationToken cancellationToken)
{
- if (!response.Headers.TryGetValues("server-timing", out var values))
- return null;
- foreach (var value in values)
+ return WithTimeoutAsync(async timeout =>
{
- var match = ServerTimingRegex.Match(value);
- if (match.Success && double.TryParse(match.Groups[1].Value,
- System.Globalization.NumberStyles.Float,
- System.Globalization.CultureInfo.InvariantCulture, out var dur))
- return dur;
- }
- return null;
+ var sw = Stopwatch.StartNew();
+ using var request = new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/__down?bytes=0");
+ using var response = await _client
+ .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token)
+ .ConfigureAwait(false);
+ sw.Stop();
+ var ttfb = sw.Elapsed.TotalMilliseconds;
+ EnsureSuccess(response);
+ await response.Content.CopyToAsync(Stream.Null, timeout.Token).ConfigureAwait(false);
+
+ var serverTime = ParseServerTiming(response.Headers) ?? DefaultEstimatedServerTimeMs;
+ var ping = ttfb - serverTime;
+ if (ping < 0) ping = 0;
+ pings.Add(ping);
+
+ return true;
+ }, cancellationToken);
}
- private static double Percentile(List values, double p)
+ private Task<(double Bps, double DurationMs)> MeasureDownloadAsync(int bytes,
+ CancellationToken cancellationToken, Action onLiveBps)
{
- if (values == null || values.Count == 0)
- return 0.0;
- var sorted = values.OrderBy(v => v).ToList();
- if (sorted.Count == 1)
- return sorted[0];
- var rank = p * (sorted.Count - 1);
- var lower = (int)Math.Floor(rank);
- var upper = (int)Math.Ceiling(rank);
- if (lower == upper)
- return sorted[lower];
- var weight = rank - lower;
- return sorted[lower] * (1 - weight) + sorted[upper] * weight;
+ return WithTimeoutAsync(async timeout =>
+ {
+ var sw1 = Stopwatch.StartNew();
+ using var request = new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/__down?bytes={bytes}");
+ using var response = await _client
+ .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token)
+ .ConfigureAwait(false);
+ sw1.Stop();
+ var ttfb = sw1.Elapsed.TotalMilliseconds;
+ EnsureSuccess(response);
+ var serverTime = ParseServerTiming(response.Headers) ?? DefaultEstimatedServerTimeMs;
+ var ping = ttfb - serverTime;
+ if (ping < 0) ping = 0;
+
+ var sw2 = Stopwatch.StartNew();
+ long bodyBytes;
+ double lastProgressMs = 0;
+ long lastProgressBytes = 0;
+ await using (var stream = await response.Content
+ .ReadAsStreamAsync(timeout.Token).ConfigureAwait(false))
+ {
+ var buffer = new byte[81920];
+ long total = 0;
+ int read;
+ while ((read = await stream.ReadAsync(buffer, timeout.Token)
+ .ConfigureAwait(false)) > 0)
+ {
+ total += read;
+ timeout.CancelAfter(RequestTimeout);
+ var elapsedMs = sw2.Elapsed.TotalMilliseconds;
+ if (onLiveBps != null && elapsedMs - lastProgressMs >= LiveProgressIntervalMs
+ && elapsedMs > 0)
+ {
+ // Instantaneous throughput over the last interval (delta-based)
+ var deltaBytes = total - lastProgressBytes;
+ var deltaMs = elapsedMs - lastProgressMs;
+ var liveBps = 8.0 * deltaBytes / (deltaMs / 1000.0);
+ onLiveBps(liveBps);
+ lastProgressMs = elapsedMs;
+ lastProgressBytes = total;
+ }
+ }
+ bodyBytes = total;
+ }
+ sw2.Stop();
+ var bodyMs = sw2.Elapsed.TotalMilliseconds;
+
+ var downloadDurationMs = ping + bodyMs;
+ if (downloadDurationMs <= 0)
+ return (0.0, downloadDurationMs);
+
+ // Received bytes incl. an estimate of the headers (the official library uses the transfer size of the browser)
+ var bps = 8.0 * bodyBytes * EstimatedHeaderFraction / (downloadDurationMs / 1000.0);
+ return (bps, downloadDurationMs);
+ }, cancellationToken);
}
- private static double Jitter(List pings)
+ private Task<(double Bps, double DurationMs)> MeasureUploadAsync(int bytes,
+ CancellationToken cancellationToken)
{
- if (pings == null || pings.Count < 2)
- return 0.0;
- double sum = 0;
- for (var i = 1; i < pings.Count; i++)
- sum += Math.Abs(pings[i] - pings[i - 1]);
- return sum / (pings.Count - 1);
+ return WithTimeoutAsync(async timeout =>
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Post, $"{BaseUrl}/__up");
+ using var content = new ZeroStreamContent(bytes, () => timeout.CancelAfter(RequestTimeout));
+ request.Content = content;
+
+ var sw = Stopwatch.StartNew();
+ using var response = await _client
+ .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token)
+ .ConfigureAwait(false);
+ sw.Stop();
+ var ttfb = sw.Elapsed.TotalMilliseconds;
+ EnsureSuccess(response);
+ await response.Content.CopyToAsync(Stream.Null, timeout.Token).ConfigureAwait(false);
+
+ var uploadDurationMs = ttfb;
+ if (uploadDurationMs <= 0)
+ return (0.0, uploadDurationMs);
+
+ var bps = 8.0 * bytes * EstimatedHeaderFraction / (uploadDurationMs / 1000.0);
+ return (bps, uploadDurationMs);
+ }, cancellationToken);
}
#endregion
@@ -405,11 +524,15 @@ private static double Jitter(List pings)
private sealed class ZeroStreamContent : HttpContent
{
private readonly int _length;
+ private readonly Action _onWritten;
private static readonly byte[] _chunk = new byte[81920];
- internal ZeroStreamContent(int length)
+ /// Number of bytes.
+ /// Called after each written chunk (e.g. to restart a timeout).
+ internal ZeroStreamContent(int length, Action onWritten)
{
_length = length;
+ _onWritten = onWritten;
Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
Headers.ContentLength = length;
}
@@ -426,6 +549,7 @@ protected override async Task SerializeToStreamAsync(Stream stream, TransportCon
var toWrite = Math.Min(_chunk.Length, remaining);
await stream.WriteAsync(_chunk.AsMemory(0, toWrite), cancellationToken).ConfigureAwait(false);
remaining -= toWrite;
+ _onWritten?.Invoke();
}
}
diff --git a/Source/NETworkManager.Tests/Cloudflare/SpeedTestCalculatorTests.cs b/Source/NETworkManager.Tests/Cloudflare/SpeedTestCalculatorTests.cs
new file mode 100644
index 0000000000..6682e71a0c
--- /dev/null
+++ b/Source/NETworkManager.Tests/Cloudflare/SpeedTestCalculatorTests.cs
@@ -0,0 +1,202 @@
+using System;
+using System.IO;
+using System.Net;
+using System.Net.Http;
+using NETworkManager.Models.Cloudflare;
+using Xunit;
+
+namespace NETworkManager.Tests.Cloudflare;
+
+public class SpeedTestCalculatorTests
+{
+ [Fact]
+ public void PercentileOfNoValuesIsZero()
+ {
+ Assert.Equal(0, SpeedTestCalculator.Percentile([], 0.9));
+ }
+
+ [Fact]
+ public void PercentileOfOneValueIsTheValue()
+ {
+ Assert.Equal(42, SpeedTestCalculator.Percentile([42], 0.9));
+ }
+
+ [Fact]
+ public void PercentileOnARankIsTheValue()
+ {
+ // Rank 0.5 * (5 - 1) = 2 → third value of the sorted list
+ Assert.Equal(3, SpeedTestCalculator.Percentile([5, 1, 4, 2, 3], 0.5));
+ }
+
+ [Fact]
+ public void PercentileBetweenRanksIsInterpolated()
+ {
+ // Rank 0.9 * (10 - 1) = 8.1 → 9 + 0.1 * (10 - 9)
+ Assert.Equal(9.1, SpeedTestCalculator.Percentile([10, 9, 8, 7, 6, 5, 4, 3, 2, 1], 0.9), 10);
+ }
+
+ [Fact]
+ public void CurrentBandwidthWithoutValuesIsNull()
+ {
+ Assert.Null(SpeedTestCalculator.CurrentBandwidth([], null));
+ }
+
+ [Fact]
+ public void CurrentBandwidthBeforeTheFirstSampleIsTheLiveValue()
+ {
+ Assert.Equal(50, SpeedTestCalculator.CurrentBandwidth([], 50));
+ }
+
+ [Fact]
+ public void CurrentBandwidthWithSamplesIgnoresAHigherLiveValue()
+ {
+ // A burst of the running request must not be shown above the result (P90 of the samples)
+ Assert.Equal(100, SpeedTestCalculator.CurrentBandwidth([100], 480));
+ }
+
+ [Fact]
+ public void DirectionIsNotFinishedWithoutRequests()
+ {
+ Assert.False(SpeedTestCalculator.IsDirectionFinished([], 1000));
+ }
+
+ [Fact]
+ public void DirectionIsNotFinishedIfOneRequestWasFaster()
+ {
+ // The first slow request (e.g. TCP slow start) doesn't end the direction, the whole set decides
+ Assert.False(SpeedTestCalculator.IsDirectionFinished([1200, 900, 1100], 1000));
+ }
+
+ [Fact]
+ public void DirectionIsNotFinishedAtExactlyTheFinishDuration()
+ {
+ Assert.False(SpeedTestCalculator.IsDirectionFinished([1000, 1500], 1000));
+ }
+
+ [Fact]
+ public void DirectionIsFinishedIfAllRequestsWereSlower()
+ {
+ Assert.True(SpeedTestCalculator.IsDirectionFinished([1200, 1100, 1300], 1000));
+ }
+
+ private static readonly DateTimeOffset Now = new(2026, 11, 26, 12, 0, 0, TimeSpan.Zero);
+
+ [Fact]
+ public void RetryDelayWithoutHeaderIsFiveSeconds()
+ {
+ Assert.Equal(TimeSpan.FromSeconds(5), SpeedTestCalculator.GetRetryDelay(null, null, Now));
+ }
+
+ [Fact]
+ public void RetryDelayIsTheDeltaOfTheHeader()
+ {
+ Assert.Equal(TimeSpan.FromSeconds(2), SpeedTestCalculator.GetRetryDelay(TimeSpan.FromSeconds(2), null, Now));
+ }
+
+ [Fact]
+ public void RetryDelayIsTheTimeUntilTheDateOfTheHeader()
+ {
+ Assert.Equal(TimeSpan.FromSeconds(10),
+ SpeedTestCalculator.GetRetryDelay(null, Now.AddSeconds(10), Now));
+ }
+
+ [Fact]
+ public void RetryDelayOfADateInThePastIsZero()
+ {
+ Assert.Equal(TimeSpan.Zero, SpeedTestCalculator.GetRetryDelay(null, Now.AddSeconds(-10), Now));
+ }
+
+ [Fact]
+ public void RetryDelayIsAtMostSixtySeconds()
+ {
+ Assert.Equal(TimeSpan.FromSeconds(60),
+ SpeedTestCalculator.GetRetryDelay(TimeSpan.FromHours(1), null, Now));
+ }
+
+ [Fact]
+ public void HttpErrorIsNoConnectionFailure()
+ {
+ // e.g. a proxy rejects a large upload (413): the connection works, the test continues
+ Assert.False(SpeedTestCalculator.IsConnectionFailure(
+ new HttpRequestException("Payload too large", null, HttpStatusCode.RequestEntityTooLarge)));
+ }
+
+ [Fact]
+ public void NoResponseIsAConnectionFailure()
+ {
+ Assert.True(SpeedTestCalculator.IsConnectionFailure(new HttpRequestException("No such host is known.")));
+ Assert.True(SpeedTestCalculator.IsConnectionFailure(new IOException("Connection reset")));
+ Assert.True(SpeedTestCalculator.IsConnectionFailure(new TimeoutException()));
+ }
+
+ [Fact]
+ public void JitterOfFewerThanTwoPingsIsZero()
+ {
+ Assert.Equal(0, SpeedTestCalculator.Jitter([]));
+ Assert.Equal(0, SpeedTestCalculator.Jitter([10]));
+ }
+
+ [Fact]
+ public void JitterIsTheAverageConsecutiveDifference()
+ {
+ // |12 - 10| + |9 - 12| + |9 - 9| = 5, 3 differences
+ Assert.Equal(5.0 / 3, SpeedTestCalculator.Jitter([10, 12, 9, 9]), 10);
+ }
+
+ [Fact]
+ public void ServerTimingWithoutHeaderIsNull()
+ {
+ Assert.Null(SpeedTestCalculator.ParseServerTiming(null));
+ Assert.Null(SpeedTestCalculator.ParseServerTiming([]));
+ }
+
+ [Fact]
+ public void ServerTimingIsTheRequestDuration()
+ {
+ Assert.Equal(12.5, SpeedTestCalculator.ParseServerTiming(["cfRequestDuration;dur=12.5"]));
+ }
+
+ [Fact]
+ public void ServerTimingIsTheRequestDurationAfterOtherMetrics()
+ {
+ Assert.Equal(12.5,
+ SpeedTestCalculator.ParseServerTiming(["cfL4;desc=\"?proto=TCP&rtt=11\";dur=5, cfRequestDuration;dur=12.5"]));
+ }
+
+ [Fact]
+ public void ServerTimingAcceptsTheShortName()
+ {
+ Assert.Equal(3, SpeedTestCalculator.ParseServerTiming(["cfReqDur;dur=3"]));
+ }
+
+ [Fact]
+ public void ServerTimingIsTheSumOfTheSpeedDurationsWithoutRequestDuration()
+ {
+ Assert.Equal(3.5, SpeedTestCalculator.ParseServerTiming(["cfSpeedA;dur=1.5, cfSpeedB;dur=2"])!.Value, 10);
+ }
+
+ [Fact]
+ public void ServerTimingReadsAllHeaderValues()
+ {
+ Assert.Equal(7, SpeedTestCalculator.ParseServerTiming(["cfL4;dur=1", "cfRequestDuration;dur=7"]));
+ }
+
+ [Fact]
+ public void ServerTimingOfOtherMetricsIsNull()
+ {
+ Assert.Null(SpeedTestCalculator.ParseServerTiming(["cfL4;dur=5, cfCacheStatus;dur=1"]));
+ }
+
+ [Fact]
+ public void ServerTimingUpToTheMinimumIsIgnored()
+ {
+ Assert.Equal(2, SpeedTestCalculator.ParseServerTiming(["cfRequestDuration;dur=0.01, cfSpeedA;dur=2"]));
+ Assert.Null(SpeedTestCalculator.ParseServerTiming(["cfSpeedA;dur=0.005"]));
+ }
+
+ [Fact]
+ public void ServerTimingWithInvalidDurationIsNull()
+ {
+ Assert.Null(SpeedTestCalculator.ParseServerTiming(["cfRequestDuration;dur=."]));
+ }
+}
diff --git a/Source/NETworkManager.Tests/Cloudflare/SpeedTestMetaInfoTests.cs b/Source/NETworkManager.Tests/Cloudflare/SpeedTestMetaInfoTests.cs
new file mode 100644
index 0000000000..ca9d80d06f
--- /dev/null
+++ b/Source/NETworkManager.Tests/Cloudflare/SpeedTestMetaInfoTests.cs
@@ -0,0 +1,30 @@
+using NETworkManager.Models.Cloudflare;
+using Newtonsoft.Json;
+using Xunit;
+
+namespace NETworkManager.Tests.Cloudflare;
+
+public class SpeedTestMetaInfoTests
+{
+ [Fact]
+ public void MetaWithAllValues()
+ {
+ var meta = JsonConvert.DeserializeObject(
+ """{"clientIp":"203.0.113.1","asn":64496,"asOrganization":"Example ISP","country":"DE","city":"Bochum","colo":{"iata":"FRA","city":"Frankfurt-am-Main","cca2":"DE"}}""");
+
+ Assert.Equal(64496, meta.Asn);
+ Assert.Equal("Example ISP", meta.AsOrganization);
+ Assert.Equal("FRA", meta.Colo.Iata);
+ }
+
+ [Fact]
+ public void MetaWithoutAsnAndServer()
+ {
+ // No ASN (e.g. unknown network) must not fail the speed test
+ var meta = JsonConvert.DeserializeObject("""{"asn":null,"asOrganization":"Example ISP"}""");
+
+ Assert.Null(meta.Asn);
+ Assert.Null(meta.Colo);
+ Assert.Equal("Example ISP", meta.AsOrganization);
+ }
+}
diff --git a/Source/NETworkManager.Tests/Cloudflare/SpeedTestResultTests.cs b/Source/NETworkManager.Tests/Cloudflare/SpeedTestResultTests.cs
new file mode 100644
index 0000000000..004d55946b
--- /dev/null
+++ b/Source/NETworkManager.Tests/Cloudflare/SpeedTestResultTests.cs
@@ -0,0 +1,41 @@
+using NETworkManager.Models.Cloudflare;
+using Xunit;
+
+namespace NETworkManager.Tests.Cloudflare;
+
+public class SpeedTestResultTests
+{
+ [Fact]
+ public void ServerWithAllValues()
+ {
+ Assert.Equal("Frankfurt-am-Main, DE (FRA)",
+ new SpeedTestResult { ServerCity = "Frankfurt-am-Main", ServerCountry = "DE", ServerIata = "FRA" }.Server);
+ }
+
+ [Fact]
+ public void ServerWithoutValuesIsNull()
+ {
+ // Shown as "-/-" instead of "-/-, -/- (-/-)"
+ Assert.Null(new SpeedTestResult().Server);
+ Assert.Null(new SpeedTestResult { ServerCity = " ", ServerCountry = "" }.Server);
+ }
+
+ [Fact]
+ public void ServerWithoutCity()
+ {
+ Assert.Equal("DE (FRA)", new SpeedTestResult { ServerCountry = "DE", ServerIata = "FRA" }.Server);
+ }
+
+ [Fact]
+ public void ServerWithOnlyTheCode()
+ {
+ Assert.Equal("FRA", new SpeedTestResult { ServerIata = "FRA" }.Server);
+ }
+
+ [Fact]
+ public void ServerWithoutCode()
+ {
+ Assert.Equal("Frankfurt-am-Main, DE",
+ new SpeedTestResult { ServerCity = "Frankfurt-am-Main", ServerCountry = "DE" }.Server);
+ }
+}
diff --git a/Source/NETworkManager/ScreenshotData.cs b/Source/NETworkManager/ScreenshotData.cs
index 9c3790e9cd..ec2440aeb6 100644
--- a/Source/NETworkManager/ScreenshotData.cs
+++ b/Source/NETworkManager/ScreenshotData.cs
@@ -327,8 +327,6 @@ public static SpeedTestResult CreateSpeedTestResult()
LatencyMs = 12.4,
JitterMs = 1.8,
Isp = Isp,
- ClientCity = "Frankfurt am Main",
- ClientCountry = "DE",
ServerCity = "Frankfurt",
ServerCountry = "DE",
ServerIata = "FRA"
diff --git a/Source/NETworkManager/ViewModels/SpeedTestWidgetViewModel.cs b/Source/NETworkManager/ViewModels/SpeedTestWidgetViewModel.cs
index ef883f4ded..ca97056c97 100644
--- a/Source/NETworkManager/ViewModels/SpeedTestWidgetViewModel.cs
+++ b/Source/NETworkManager/ViewModels/SpeedTestWidgetViewModel.cs
@@ -1,6 +1,7 @@
using System;
-using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Net.Http;
+using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
@@ -9,6 +10,7 @@
using LiveChartsCore.Kernel.Sketches;
using LiveChartsCore.SkiaSharpView;
using log4net;
+using NETworkManager.Controls;
using NETworkManager.Localization.Resources;
using NETworkManager.Models.Cloudflare;
using NETworkManager.Settings;
@@ -59,6 +61,22 @@ public bool ShowDisclaimer
}
} = true;
+ ///
+ /// Time of the last completed test, null before the first one.
+ ///
+ public DateTime? LastTestTime
+ {
+ get;
+ private set
+ {
+ if (value == field)
+ return;
+
+ field = value;
+ OnPropertyChanged();
+ }
+ }
+
public SpeedTestResult Result
{
get;
@@ -75,6 +93,25 @@ private set
public bool HasResult => Result != null;
+ ///
+ /// Phase of the running test (e.g. "Measuring download speed...").
+ ///
+ public string PhaseMessage
+ {
+ get;
+ private set
+ {
+ if (value == field)
+ return;
+
+ field = value;
+ OnPropertyChanged();
+ }
+ }
+
+ ///
+ /// Message after the test, e.g. canceled by the user or an error.
+ ///
public string StatusMessage
{
get;
@@ -88,6 +125,32 @@ private set
}
}
+ public StatusLevel StatusMessageLevel
+ {
+ get;
+ private set
+ {
+ if (value == field)
+ return;
+
+ field = value;
+ OnPropertyChanged();
+ }
+ }
+
+ public bool IsStatusMessageDisplayed
+ {
+ get;
+ private set
+ {
+ if (value == field)
+ return;
+
+ field = value;
+ OnPropertyChanged();
+ }
+ }
+
public double? CurrentDownloadMbps
{
get;
@@ -152,14 +215,23 @@ private set
/// LiveCharts2 series for the upload sparkline.
public ISeries[] UploadSeries { get; }
- /// Hidden X-axes for the download sparkline (anchored at 0 so the first sample sits at the left edge).
- public ICartesianAxis[] DownloadXAxes { get; } = [new Axis { IsVisible = false, MinLimit = 0, MinStep = 1 }];
+ ///
+ /// X axis of the download sparkline (sample index, hidden). From 0 to at least 1, so the first sample is at the left
+ /// edge instead of in the middle of the chart.
+ ///
+ private readonly Axis _downloadXAxis = new() { IsVisible = false, MinLimit = 0, MaxLimit = 1, MinStep = 1 };
+
+ /// X axis of the upload sparkline, see .
+ private readonly Axis _uploadXAxis = new() { IsVisible = false, MinLimit = 0, MaxLimit = 1, MinStep = 1 };
+
+ /// Hidden X-axes for the download sparkline.
+ public ICartesianAxis[] DownloadXAxes { get; }
/// Hidden Y-axes for the download sparkline.
public ICartesianAxis[] DownloadYAxes { get; } = [new Axis { IsVisible = false, MinLimit = 0 }];
/// Hidden X-axes for the upload sparkline.
- public ICartesianAxis[] UploadXAxes { get; } = [new Axis { IsVisible = false, MinLimit = 0, MinStep = 1 }];
+ public ICartesianAxis[] UploadXAxes { get; }
/// Hidden Y-axes for the upload sparkline.
public ICartesianAxis[] UploadYAxes { get; } = [new Axis { IsVisible = false, MinLimit = 0 }];
@@ -168,8 +240,37 @@ private set
public ICommand AcceptDisclaimerCommand => field ??= new RelayCommand(_ => AcceptDisclaimerAction());
+ ///
+ /// Copies all values of the test (also of a canceled test), e.g. for a support request.
+ ///
+ public ICommand CopyAllCommand => field ??= new RelayCommand(_ => CopyAllAction(),
+ _ => !IsRunning && (Result != null || CurrentLatencyMs != null));
+
+ private void CopyAllAction()
+ {
+ static string Format(double? value, string format, string unit) =>
+ value.HasValue ? $"{value.Value.ToString(format)} {unit}" : "-/-";
+
+ var text = new StringBuilder();
+
+ text.AppendLine($"{Strings.Download}: {Format(CurrentDownloadMbps, "F1", "Mbps")}");
+ text.AppendLine($"{Strings.Upload}: {Format(CurrentUploadMbps, "F1", "Mbps")}");
+ text.AppendLine($"{Strings.Latency}: {Format(CurrentLatencyMs, "F0", "ms")}");
+ text.AppendLine($"{Strings.Jitter}: {Format(CurrentJitterMs, "F1", "ms")}");
+ text.AppendLine($"{Strings.ISP}: {Result?.Isp ?? "-/-"}");
+ text.AppendLine($"{Strings.Server}: {Result?.Server ?? "-/-"}");
+
+ if (LastTestTime is { } time)
+ text.AppendLine(string.Format(Strings.LastTestAtX, time.ToString("G")));
+
+ ClipboardHelper.SetClipboard(text.ToString().TrimEnd());
+ }
+
public SpeedTestWidgetViewModel()
{
+ DownloadXAxes = [_downloadXAxis];
+ UploadXAxes = [_uploadXAxis];
+
var downloadColor = ChartColors.Primary;
DownloadSeries =
[
@@ -226,7 +327,7 @@ private void RunAction()
{
if (IsRunning)
{
- _cts?.Cancel();
+ Cancel();
return;
}
@@ -236,6 +337,15 @@ private void RunAction()
_ = RunAsync();
}
+ ///
+ /// Cancels a running speed test, the values measured until then stay visible.
+ ///
+ public void Cancel()
+ {
+ if (IsRunning)
+ _cts?.Cancel();
+ }
+
///
/// Shows the sample result of instead of running a real speed test.
///
@@ -243,26 +353,60 @@ private void SetScreenshotData()
{
var result = ScreenshotData.CreateSpeedTestResult();
- // Seed the first point twice, like a real test (see RunAsync)
- AddScreenshotSamples(DownloadSamples, ScreenshotData.CreateSpeedTestDownloadSamples());
- AddScreenshotSamples(UploadSamples, ScreenshotData.CreateSpeedTestUploadSamples());
+ foreach (var value in ScreenshotData.CreateSpeedTestDownloadSamples())
+ AddSample(DownloadSamples, _downloadXAxis, value);
+
+ foreach (var value in ScreenshotData.CreateSpeedTestUploadSamples())
+ AddSample(UploadSamples, _uploadXAxis, value);
Result = result;
+ LastTestTime = DateTime.Now;
CurrentDownloadMbps = result.DownloadMbps;
CurrentUploadMbps = result.UploadMbps;
CurrentLatencyMs = result.LatencyMs;
CurrentJitterMs = result.JitterMs;
}
- private static void AddScreenshotSamples(ObservableCollection samples, IEnumerable values)
+ private void ShowStatusMessage(string message, StatusLevel level)
+ {
+ StatusMessage = message;
+ StatusMessageLevel = level;
+ IsStatusMessageDisplayed = true;
+ }
+
+ ///
+ /// Localized message for an error of the speed test (the exception text is logged).
+ ///
+ private static string GetErrorMessage(Exception ex)
{
- foreach (var value in values)
+ var message = ex switch
{
- if (samples.Count == 0)
- samples.Add(value);
+ TimeoutException => string.Format(Strings.XXXDidNotRespondWithinXXXSecondsMessage, SpeedTestService.Host,
+ SpeedTestService.RequestTimeout.TotalSeconds),
+ HttpRequestException { StatusCode: not null } httpEx => string.Format(Strings.CouldNotConnectToXXXReasonXXX,
+ SpeedTestService.Host, $"{Strings.HTTPStatusCode} {(int)httpEx.StatusCode}"),
+ _ => string.Format(Strings.CouldNotConnectToXXXMessage, SpeedTestService.Host)
+ };
+
+ // One message with its hint (a new line would look like a second message), wraps if the widget is narrow
+ return $"{message} {Strings.CheckNetworkConnectionTryAgainMessage}";
+ }
- samples.Add(value);
- }
+ ///
+ /// Adds a sample (one completed request) to a sparkline and extends its X axis to the samples.
+ ///
+ private static void AddSample(ObservableCollection samples, Axis xAxis, double value)
+ {
+ samples.Add(value);
+ xAxis.MaxLimit = Math.Max(1, samples.Count - 1);
+ }
+
+ private void ClearSamples()
+ {
+ DownloadSamples.Clear();
+ UploadSamples.Clear();
+ _downloadXAxis.MaxLimit = 1;
+ _uploadXAxis.MaxLimit = 1;
}
private void AcceptDisclaimerAction()
@@ -278,18 +422,22 @@ private async Task RunAsync()
IsRunning = true;
Result = null;
+
+ // The time belongs to the values shown: a canceled / failed test shows its partial values without a time
+ LastTestTime = null;
CurrentDownloadMbps = null;
CurrentUploadMbps = null;
CurrentLatencyMs = null;
CurrentJitterMs = null;
- DownloadSamples.Clear();
- UploadSamples.Clear();
- StatusMessage = Strings.FetchingMetadataDots;
+ ClearSamples();
+ IsStatusMessageDisplayed = false;
+ PhaseMessage = Strings.FetchingMetadataDots;
if (ScreenshotData.IsEnabled)
{
SetScreenshotData();
IsRunning = false;
+ CommandManager.InvalidateRequerySuggested();
return;
}
@@ -298,7 +446,7 @@ private async Task RunAsync()
var progress = new Progress(p =>
{
- StatusMessage = p.Phase switch
+ PhaseMessage = p.Phase switch
{
SpeedTestPhase.FetchingMetadata => Strings.FetchingMetadataDots,
SpeedTestPhase.MeasuringLatency => Strings.MeasuringLatencyDots,
@@ -317,30 +465,18 @@ private async Task RunAsync()
CurrentJitterMs = p.JitterMs;
if (p.NewDownloadSampleMbps.HasValue)
- {
- // Seed the first point twice so LiveCharts2 renders the sparkline
- // anchored at x=0 rather than starting mid-chart on the first sample.
- if (DownloadSamples.Count == 0)
- DownloadSamples.Add(p.NewDownloadSampleMbps.Value);
- DownloadSamples.Add(p.NewDownloadSampleMbps.Value);
- }
+ AddSample(DownloadSamples, _downloadXAxis, p.NewDownloadSampleMbps.Value);
+
if (p.NewUploadSampleMbps.HasValue)
- {
- // Same workaround as above for the upload sparkline.
- if (UploadSamples.Count == 0)
- UploadSamples.Add(p.NewUploadSampleMbps.Value);
- UploadSamples.Add(p.NewUploadSampleMbps.Value);
- }
+ AddSample(UploadSamples, _uploadXAxis, p.NewUploadSampleMbps.Value);
if (p.Meta != null)
{
// Populate Result with metadata-only fields so the UI can
- // show ISP / location / server while measurements are still running.
+ // show ISP / server while measurements are still running.
Result = new SpeedTestResult
{
Isp = p.Meta.AsOrganization,
- ClientCity = p.Meta.City,
- ClientCountry = p.Meta.Country,
ServerCity = p.Meta.Colo?.City,
ServerCountry = p.Meta.Colo?.Cca2,
ServerIata = p.Meta.Colo?.Iata
@@ -352,27 +488,33 @@ private async Task RunAsync()
{
var result = await _service.RunAsync(progress, _cts.Token);
Result = result;
+ LastTestTime = DateTime.Now;
CurrentDownloadMbps = result.DownloadMbps;
CurrentUploadMbps = result.UploadMbps;
CurrentLatencyMs = result.LatencyMs;
CurrentJitterMs = result.JitterMs;
+
+ if (result.FailedRequests > 0)
+ ShowStatusMessage(string.Format(Strings.XRequestsFailedAndWereSkippedMessage, result.FailedRequests),
+ StatusLevel.Warning);
}
catch (OperationCanceledException)
{
// Partial results remain visible; everything resets at the start of the next run.
+ ShowStatusMessage(Strings.CanceledByUserMessage, StatusLevel.None);
}
catch (Exception ex)
{
+ // Partial results remain visible, like after a cancel
Log.Error("Speed test failed.", ex);
- Result = new SpeedTestResult
- {
- HasError = true,
- ErrorMessage = ex.Message
- };
+ ShowStatusMessage(GetErrorMessage(ex), StatusLevel.Error);
}
finally
{
IsRunning = false;
+
+ // Enable copy all (CanExecute is otherwise only evaluated on the next input)
+ CommandManager.InvalidateRequerySuggested();
}
}
}
diff --git a/Source/NETworkManager/Views/DashboardView.xaml.cs b/Source/NETworkManager/Views/DashboardView.xaml.cs
index f14d2c0129..655c74fdee 100644
--- a/Source/NETworkManager/Views/DashboardView.xaml.cs
+++ b/Source/NETworkManager/Views/DashboardView.xaml.cs
@@ -194,5 +194,11 @@ private void SettingsManager_PropertyChanged(object sender, PropertyChangedEvent
{
if (e.PropertyName != null && NetworkConnectionSettings.Contains(e.PropertyName))
_isOutdated = true;
+
+ // A hidden speed test widget doesn't measure (no data is transferred in the background): cancel it right away,
+ // the dashboard is hidden while the settings are open
+ if (e.PropertyName == nameof(SettingsInfo.Dashboard_ShowSpeedTestWidget) &&
+ !SettingsManager.Current.Dashboard_ShowSpeedTestWidget)
+ _speedTestWidgetView?.Cancel();
}
}
\ No newline at end of file
diff --git a/Source/NETworkManager/Views/SpeedTestWidgetView.xaml b/Source/NETworkManager/Views/SpeedTestWidgetView.xaml
index b1b9cfb2e7..dce4aae1bf 100644
--- a/Source/NETworkManager/Views/SpeedTestWidgetView.xaml
+++ b/Source/NETworkManager/Views/SpeedTestWidgetView.xaml
@@ -13,7 +13,6 @@
mc:Ignorable="d" MinHeight="200"
d:DataContext="{d:DesignInstance viewModels:SpeedTestWidgetViewModel}">
-
@@ -29,7 +28,8 @@
-
+
+
@@ -51,70 +51,98 @@
Style="{StaticResource MessageTextBlock}"
Margin="10,0,0,0" />
-
+
+
+
-
-
+
+
-
-
+
+
+
+
+
+
+
-
+
@@ -144,47 +172,8 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
@@ -215,15 +204,9 @@
Text="{Binding Result.Isp, TargetNullValue=-/-, FallbackValue=-/-, Mode=OneWay}" />
-
-
-
-
-
-
-
-
-
+
+ /// Cancels a running speed test (e.g. the widget was hidden in the settings).
+ ///
+ public void Cancel()
+ {
+ _viewModel.Cancel();
+ }
}
diff --git a/Website/docs/application/dashboard.md b/Website/docs/application/dashboard.md
index acf4f598d8..d69814f351 100644
--- a/Website/docs/application/dashboard.md
+++ b/Website/docs/application/dashboard.md
@@ -125,7 +125,7 @@ Enables or disables the detection of the DNS resolver in use via [`ip-api.com`](
### Widgets
-Show or hide the widgets on the dashboard: **Network connection**, **Speed Test**, **IP geolocation** and **DNS resolver**. A hidden widget doesn't check anything (e.g. no request is sent to `ip-api.com`); a speed test that is already running when the widget is hidden is completed. If one of IP geolocation and DNS resolver is hidden, the other one uses the whole width. The status window always shows the network connection.
+Show or hide the widgets on the dashboard: **Network connection**, **Speed Test**, **IP geolocation** and **DNS resolver**. A hidden widget doesn't check anything (e.g. no request is sent to `ip-api.com`); a speed test that is running when the widget is hidden is canceled. If one of IP geolocation and DNS resolver is hidden, the other one uses the whole width. The status window always shows the network connection.
**Type:** `Boolean`
@@ -133,22 +133,33 @@ Show or hide the widgets on the dashboard: **Network connection**, **Speed Test*
## Speed Test
-The **Speed Test** widget measures the current connection's download and upload speed, latency, and jitter against [`speed.cloudflare.com`](https://speed.cloudflare.com/). The test is **user-initiated** — it does not run automatically on dashboard load. Click **Speed Test** to run a measurement.
+The **Speed Test** widget measures the download and upload speed, latency and jitter of the current connection against [`speed.cloudflare.com`](https://speed.cloudflare.com/). The test only runs when you start it, not when the dashboard is opened.
+
+Before the first test, a privacy disclaimer informs you that `speed.cloudflare.com` receives requests with your IP address and network information. Click **Speed Test** to accept it and run the first test. The disclaimer is shown again after restarting the application (the acceptance is not saved). See the [Cloudflare privacy policy](https://www.cloudflare.com/privacypolicy/) for details. The widget never contacts Cloudflare's telemetry endpoint (`aim.cloudflare.com`).
+
+The buttons in the header of the widget:
+
+- **Run speed test** (refresh icon) starts a new test, while a test runs the button stops it (**Stop**). The values measured until then stay visible.
+- **Copy all** copies all values and the time of the test as text, e.g. for a support request.
+
+While the test runs, the header shows the current phase (latency, download, upload), afterwards the time of the test (**Last test at ...**, the tooltip shows the date; not after a canceled or failed test). A canceled or failed test and requests that failed are shown below the header.
The result includes:
-- **Download** speed in Mbps
-- **Upload** speed in Mbps
-- **Latency** in ms (unloaded, 50th percentile of latency probes)
-- **Jitter** in ms (average consecutive delta between latency samples)
+- **Download** speed in Mbps, with a chart of the requests (hover over it to see the speed of a request)
+- **Upload** speed in Mbps, with a chart of the requests
+- **Latency** in ms (unloaded, 50th percentile of the latency probes)
+- **Jitter** in ms (average difference between consecutive latency probes)
- **ISP** — internet service provider as reported by Cloudflare
-- **Server location** — Cloudflare PoP (Point of Presence) handling the test
+- **Server** — Cloudflare server (city, country and airport code) that handles the test
+
+The test measures like the official [cloudflare/speedtest](https://github.com/cloudflare/speedtest) library (used by [speed.cloudflare.com](https://speed.cloudflare.com/)), so the results are comparable: latency probes (empty downloads) and downloads / uploads of increasing size (100 kB up to 250 MB) one after the other, with a few latency probes between them. Download and upload are the 90th percentile of the requests that took at least 10 ms; the speed shown while a download runs is the result of the completed requests (only the first request is shown while it runs). A direction ends after a set of requests in which even the fastest request took longer than one second; the larger sizes are skipped.
-Before running the test, a privacy disclaimer informs the user that `speed.cloudflare.com` will receive requests with the client's IP address and network information. The disclaimer is shown again after restarting the app because acceptance is not currently persisted. See the [Cloudflare privacy policy](https://www.cloudflare.com/privacypolicy/) for details. The widget never contacts Cloudflare's telemetry endpoint (`aim.cloudflare.com/__log`).
+A test takes about 15 seconds on a fast connection and up to 1–2 minutes on a slow one. It transfers a lot of data on a fast connection: up to about 1 GB download and 300 MB upload (1 Gbit/s), keep this in mind on a metered connection (e.g. mobile data).
## Troubleshooting and limits
- The local IP address is detected by the route to the [Public IPv4 address](#public-ipv4-address) / [Public IPv6 address](#public-ipv6-address) (no packet is sent), otherwise from the first active network interface. With several network adapters (e.g. LAN and VPN), set an address that is routed via the adapter you want to see.
- The internet is shown as reachable if the [Public IPv4 address](#public-ipv4-address) / [Public IPv6 address](#public-ipv6-address) replies to the ping or the public IP address could be requested from `api.ipify.org` / `api6.ipify.org` (or the [custom API](#use-custom-ipv4-address-api)). If both are blocked (e.g. by a firewall, or websites are only reachable via a proxy), the internet is shown as a warning if Windows reports internet access (IPv4), otherwise as not reachable; use another public IP address / API. The IP geolocation and the DNS resolver are requested from `ip-api.com` (45 requests per minute).
- Without IPv6 connectivity (or no IPv6 from the internet provider), the IPv6 checks are shown as information (gray) and skipped, the IPv4 checks are not affected.
-- The [Speed Test](#speed-test) measures the connection to the nearest Cloudflare server. A VPN, a proxy or other traffic on the network at the same time lowers the result.
+- The [Speed Test](#speed-test) measures the connection to the nearest Cloudflare server. A VPN, a proxy or other traffic on the network at the same time lowers the result. A request of the speed test fails after 15 seconds without a response or data (e.g. the connection was lost). Like the official library, a failed request is skipped (shown as a warning after the test) and a request that is rate limited by Cloudflare (HTTP 429) is repeated up to three times; if all requests of a size fail (e.g. a proxy rejects large uploads), the larger sizes of the direction are skipped. After three requests in a row without a response the test ends with the error.
diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md
index 16649903eb..a4e355219f 100644
--- a/Website/docs/changelog/next-release.md
+++ b/Website/docs/changelog/next-release.md
@@ -35,7 +35,7 @@ Release date: **xx.xx.2026**
**Dashboard**
-- The widgets of the dashboard (Network connection, Speed Test, IP geolocation, DNS resolver) can be hidden in the settings (**Settings > Dashboard > Widgets**). A hidden widget doesn't check anything (a running speed test is completed). [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734)
+- The widgets of the dashboard (Network connection, Speed Test, IP geolocation, DNS resolver) can be hidden in the settings (**Settings > Dashboard > Widgets**). A hidden widget doesn't check anything (a running speed test is canceled). [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734)
## Improvements
@@ -69,6 +69,10 @@ Release date: **xx.xx.2026**
- A value of the network connection that is cut off in a narrow window (e.g. a long IPv6 address or DNS name) is shown completely in the tooltip. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734)
- The network connection shows the time of the last check ("Reloaded at ...") next to the refresh button, like other tools. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734)
- New **Copy all** button in the network connection: copies all values with the reasons of the states as text, e.g. for a support request. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734)
+- The speed test measures like the official [cloudflare/speedtest](https://github.com/cloudflare/speedtest) library, so the result is comparable with [speed.cloudflare.com](https://speed.cloudflare.com/): a download / upload direction ends after a whole set of requests in which even the fastest request took longer than one second (instead of after the first request of one second, e.g. after TCP slow start, which skipped the larger and more accurate sizes), and a few latency probes run between the sets (two instead of one at the start). The download includes an estimate of the HTTP headers (0.5 %, like the upload). The server time is read from the request duration (`cfRequestDuration`) of the `server-timing` header instead of the first duration of any metric, without it no server time is subtracted (instead of 10 ms). [#3740](https://github.com/BornToBeRoot/NETworkManager/pull/3740)
+- The speed test shows below its header when it was canceled or failed (translated, e.g. no response within 15 seconds or the HTTP status code) instead of replacing the measured values with the English error text of .NET: the values measured until then stay visible. The phase of the running test is no longer shown in the accent color. [#3740](https://github.com/BornToBeRoot/NETworkManager/pull/3740)
+- The speed test shows the time of the test ("Last test at ...") next to its buttons, like the network connection, so an old result is recognized (the tooltip shows the date). A canceled or failed test shows no time. [#3740](https://github.com/BornToBeRoot/NETworkManager/pull/3740)
+- New **Copy all** button in the speed test: copies download, upload, latency, jitter, ISP, server and the time of the test as text, like the network connection. [#3740](https://github.com/BornToBeRoot/NETworkManager/pull/3740)
**Status window**
@@ -158,6 +162,13 @@ Release date: **xx.xx.2026**
- Fixed the gateway / router not being found (shown as failed although the internet works) for VPN connections whose adapter is not an Ethernet or Wi-Fi adapter (e.g. the Windows VPN client with IKEv2 / SSTP). A VPN adapter without a gateway is no longer shown with the gateway `0.0.0.0`. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734)
- Fixed an IP address on an error page or the page of a hotspot / captive portal (e.g. hotel Wi-Fi) being shown as the public IP address. The answer of the API must have a success status code, a private IP address is shown as a warning, and an API name that can't be resolved points to the DNS server. The public IPv4 and IPv6 addresses are requested at the same time. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734)
- Fixed custom public IPv6 address APIs that answer with a JSON object (e.g. `{"ip":"2001:db8::1"}`) not being recognized. A custom API may answer with the IP address as plain text or in a JSON object; other answers (e.g. the HTML page of a captive portal) are no longer searched for an IP address. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734)
+- Fixed the speed test failing completely when the ISP / Cloudflare server could not be requested (`speed.cloudflare.com/meta`, e.g. an error of the server or a network without an ASN). The test continues, ISP and server are shown as `-/-`. [#3740](https://github.com/BornToBeRoot/NETworkManager/pull/3740)
+- Fixed the download speed of the speed test jumping above the result while the test runs (e.g. a short burst of data) and dropping at the end. The value shown is the result of the completed requests, only the first request is shown while it runs. [#3740](https://github.com/BornToBeRoot/NETworkManager/pull/3740)
+- Fixed the speed test running endlessly ("Measuring download speed...") when the connection was lost during the test (e.g. Wi-Fi disconnected). A request now fails after 15 seconds without a response or data. [#3740](https://github.com/BornToBeRoot/NETworkManager/pull/3740)
+- Fixed `Enter` on the dashboard starting a speed test (up to about 1 GB of data on a fast connection) and `Esc` stopping it, e.g. after clicking a value of another widget. The speed test is only started and stopped with its button. [#3740](https://github.com/BornToBeRoot/NETworkManager/pull/3740)
+- Fixed one failed request (e.g. a short interruption of the connection or a proxy that rejects a large upload) ending the whole speed test. Like the official library, a failed request is skipped (a warning shows how many) and a request rate limited by Cloudflare (HTTP 429) is repeated up to three times. If all requests of a size fail, the larger sizes of the direction are skipped; the test only ends after three requests in a row without a response. [#3740](https://github.com/BornToBeRoot/NETworkManager/pull/3740)
+- Fixed the server of the speed test being empty at the start of a test or shown as `-/-, -/- (-/-)` when Cloudflare did not report it. It is shown as `-/-` like the ISP, with the full name in the tooltip. [#3740](https://github.com/BornToBeRoot/NETworkManager/pull/3740)
+- Fixed the sparkline of the speed test showing the first request twice (one point more than requests, the same value twice in the tooltip). [#3740](https://github.com/BornToBeRoot/NETworkManager/pull/3740)
**Status window**