diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index d6277bc..71c2d55 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -14,12 +14,27 @@ permissions:
env:
DOTNET_VERSION: "10.0.x"
PROJECT_PATH: "NetSpeed/NetSpeed.csproj"
- LIBRESPEED_VERSION: "1.0.13"
jobs:
+ tests:
+ name: Unit tests (Linux)
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v5
+
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: ${{ env.DOTNET_VERSION }}
+
+ - name: Run NetSpeed.Core tests
+ run: dotnet test tests/NetSpeed.Core.Tests/NetSpeed.Core.Tests.csproj -c Release
+
debug:
name: Debug ${{ matrix.platform }}
runs-on: windows-2025
+ needs: tests
strategy:
fail-fast: false
@@ -27,10 +42,8 @@ jobs:
include:
- platform: x64
runtime: win-x64
- librespeed_arch: amd64
- platform: ARM64
runtime: win-arm64
- librespeed_arch: arm64
steps:
- name: Checkout repository
@@ -47,30 +60,6 @@ jobs:
dotnet restore "${{ env.PROJECT_PATH }}" -p:NuGetAuditMode=all -warnaserror:NU1901,NU1902,NU1903,NU1904
if ($LASTEXITCODE -ne 0) { throw "dotnet restore failed." }
- - name: Download and verify LibreSpeed CLI
- shell: pwsh
- run: |
- $version = "${{ env.LIBRESPEED_VERSION }}"
- $arch = "${{ matrix.librespeed_arch }}"
- $file = "librespeed-cli_${version}_windows_${arch}.zip"
- $baseUrl = "https://github.com/librespeed/speedtest-cli/releases/download/v${version}"
-
- Invoke-WebRequest -Uri "$baseUrl/$file" -OutFile $file
- Invoke-WebRequest -Uri "$baseUrl/checksums.txt" -OutFile "checksums.txt"
-
- $checksumLine = Get-Content "checksums.txt" | Where-Object { $_ -match [regex]::Escape($file) } | Select-Object -First 1
- if (-not $checksumLine) { throw "Checksum for $file not found." }
-
- $expected = ($checksumLine -split '\s+')[0].Trim().ToLowerInvariant()
- $actual = (Get-FileHash -Path $file -Algorithm SHA256).Hash.ToLowerInvariant()
- if ($expected -ne $actual) { throw "LibreSpeed CLI checksum mismatch." }
-
- $target = "NetSpeed\ThirdParty\LibreSpeed"
- Remove-Item -Path $target -Recurse -Force -ErrorAction SilentlyContinue
- New-Item -ItemType Directory -Force -Path $target | Out-Null
- Expand-Archive -Path $file -DestinationPath $target -Force
- Invoke-WebRequest -Uri "https://raw.githubusercontent.com/librespeed/speedtest-cli/v${version}/LICENSE" -OutFile "$target\LICENSE-LGPL-3.0.txt"
-
- name: Build Debug MSIX
shell: pwsh
run: |
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 1086d94..3aa2696 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -14,7 +14,6 @@ permissions:
env:
DOTNET_VERSION: "10.0.x"
PROJECT_PATH: "NetSpeed/NetSpeed.csproj"
- LIBRESPEED_VERSION: "1.0.13"
jobs:
release:
@@ -27,10 +26,8 @@ jobs:
include:
- platform: x64
runtime: win-x64
- librespeed_arch: amd64
- platform: ARM64
runtime: win-arm64
- librespeed_arch: arm64
steps:
- name: Checkout repository
@@ -48,35 +45,17 @@ jobs:
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
- - name: Restore and audit NuGet packages
+ - name: Run NetSpeed.Core tests
shell: pwsh
run: |
- dotnet restore "${{ env.PROJECT_PATH }}" -p:NuGetAuditMode=all -warnaserror:NU1901,NU1902,NU1903,NU1904
- if ($LASTEXITCODE -ne 0) { throw "dotnet restore failed." }
+ dotnet test tests/NetSpeed.Core.Tests/NetSpeed.Core.Tests.csproj -c Release
+ if ($LASTEXITCODE -ne 0) { throw "Unit tests failed." }
- - name: Download and verify LibreSpeed CLI
+ - name: Restore and audit NuGet packages
shell: pwsh
run: |
- $version = "${{ env.LIBRESPEED_VERSION }}"
- $arch = "${{ matrix.librespeed_arch }}"
- $file = "librespeed-cli_${version}_windows_${arch}.zip"
- $baseUrl = "https://github.com/librespeed/speedtest-cli/releases/download/v${version}"
-
- Invoke-WebRequest -Uri "$baseUrl/$file" -OutFile $file
- Invoke-WebRequest -Uri "$baseUrl/checksums.txt" -OutFile "checksums.txt"
-
- $checksumLine = Get-Content "checksums.txt" | Where-Object { $_ -match [regex]::Escape($file) } | Select-Object -First 1
- if (-not $checksumLine) { throw "Checksum for $file not found." }
-
- $expected = ($checksumLine -split '\s+')[0].Trim().ToLowerInvariant()
- $actual = (Get-FileHash -Path $file -Algorithm SHA256).Hash.ToLowerInvariant()
- if ($expected -ne $actual) { throw "LibreSpeed CLI checksum mismatch." }
-
- $target = "NetSpeed\ThirdParty\LibreSpeed"
- Remove-Item -Path $target -Recurse -Force -ErrorAction SilentlyContinue
- New-Item -ItemType Directory -Force -Path $target | Out-Null
- Expand-Archive -Path $file -DestinationPath $target -Force
- Invoke-WebRequest -Uri "https://raw.githubusercontent.com/librespeed/speedtest-cli/v${version}/LICENSE" -OutFile "$target\LICENSE-LGPL-3.0.txt"
+ dotnet restore "${{ env.PROJECT_PATH }}" -p:NuGetAuditMode=all -warnaserror:NU1901,NU1902,NU1903,NU1904
+ if ($LASTEXITCODE -ne 0) { throw "dotnet restore failed." }
- name: Validate signing configuration
shell: pwsh
diff --git a/.gitignore b/.gitignore
index 51d0f63..4df2e81 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,4 +5,5 @@ artifacts/
release-*/
certs/
*.pfx
-NetSpeed/ThirdParty/LibreSpeed/librespeed-cli.exe
+AppPackages/
+**/AppPackages/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2767c1d..6d0610d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,22 @@
# Changelog
+## 0.2.0 - 2026-11-27
+
+- New speed-test engine based on **Measurement Lab (M-Lab)**, written in C# with no external executables:
+ - Locate API v2 server discovery with access tokens; candidates ranked by measured round-trip time.
+ - **MSAK throughput1** with 4 parallel TCP streams for fast connections; automatic fallback to **ndt7** when MSAK has no capacity or refuses the test.
+ - Download and upload of 10 seconds each. The headline value excludes the first 2 seconds (TCP ramp-up); the full-phase average is shown as well.
+ - Upload speed from the server's own counters, as the ndt7 specification recommends.
+ - Idle latency and jitter from TCP handshakes; latency under load during download and upload; bufferbloat grade.
+- Live Mbps while the test runs, a Cancel command, and a **Copy result** command (without the IP address).
+- First-run notice explaining that M-Lab publishes test results, including the public IP address, as open data; consent is stored locally and can be withdrawn.
+- Local limit of 40 tests per 24 hours, as required by the M-Lab Acceptable Use Policy for interactive users.
+- Clear error messages for no capacity, busy servers, timeouts and network errors.
+- New platform-independent `NetSpeed.Core` library and cross-platform unit tests, run in CI.
+- New `PRIVACY.md`. Removed `SECURITY.md`, `THIRD_PARTY_NOTICES.md`, `PROJECT_INFO.txt` and `scripts/Install-Package.ps1`.
+- Developer shown as `g_`.
+- **Removed** LibreSpeed CLI, its LGPL notice and `scripts/Prepare-LibreSpeed.ps1`. The package no longer contains third-party executables.
+
## 0.1.1 - 2026-08-23
- Fixed LibreSpeed CLI 1.0.13 result parsing. The CLI returns a JSON array even when a single server is tested.
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 0d009ae..a07fd56 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -4,6 +4,7 @@
+
@@ -14,5 +15,7 @@
+
+
diff --git a/LICENSE b/LICENSE
index 0612d92..a6cfe08 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2026 Michele Gentilini
+Copyright (c) 2026 g_
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/NetSpeed.Core/LocalStateStore.cs b/NetSpeed.Core/LocalStateStore.cs
new file mode 100644
index 0000000..be303d6
--- /dev/null
+++ b/NetSpeed.Core/LocalStateStore.cs
@@ -0,0 +1,157 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace NetSpeed.Core;
+
+public sealed class LocalState
+{
+ /// Version of the data-policy notice the user accepted; 0 = never.
+ public int ConsentVersion { get; set; }
+
+ public DateTimeOffset? ConsentedAt { get; set; }
+
+ /// Start times of recent tests, for the local fair-use limit.
+ public List RecentTests { get; set; } = [];
+}
+
+[JsonSourceGenerationOptions(WriteIndented = true)]
+[JsonSerializable(typeof(LocalState))]
+internal sealed partial class LocalStateJsonContext : JsonSerializerContext
+{
+}
+
+///
+/// Persists the user's consent to the M-Lab data policy and enforces the M-Lab AUP limit for
+/// interactive users (no more than 40 tests per day, applied as a rolling 24-hour window).
+/// Everything stays on this device.
+///
+public sealed class LocalStateStore
+{
+ /// Bump when the consent text changes materially, to ask again.
+ public const int CurrentConsentVersion = 1;
+
+ public const int MaxTestsPerDay = 40;
+
+ private static readonly TimeSpan Window = TimeSpan.FromHours(24);
+
+ private readonly string _path;
+ private readonly TimeProvider _time;
+ private readonly Lock _gate = new();
+ private LocalState _state;
+
+ public LocalStateStore(string path, TimeProvider? timeProvider = null)
+ {
+ _path = path ?? throw new ArgumentNullException(nameof(path));
+ _time = timeProvider ?? TimeProvider.System;
+ _state = Load(path);
+ }
+
+ /// Default location: %LOCALAPPDATA%\NetSpeed\state.json (virtualised per package under MSIX).
+ public static string DefaultPath => Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NetSpeed", "state.json");
+
+ public bool HasConsent
+ {
+ get
+ {
+ lock (_gate)
+ {
+ return _state.ConsentVersion >= CurrentConsentVersion;
+ }
+ }
+ }
+
+ public void GrantConsent()
+ {
+ lock (_gate)
+ {
+ _state.ConsentVersion = CurrentConsentVersion;
+ _state.ConsentedAt = _time.GetUtcNow();
+ Save();
+ }
+ }
+
+ public void RevokeConsent()
+ {
+ lock (_gate)
+ {
+ _state.ConsentVersion = 0;
+ _state.ConsentedAt = null;
+ Save();
+ }
+ }
+
+ /// Tests still allowed in the current 24-hour window.
+ public int RemainingTests
+ {
+ get
+ {
+ lock (_gate)
+ {
+ Prune();
+ return Math.Max(0, MaxTestsPerDay - _state.RecentTests.Count);
+ }
+ }
+ }
+
+ /// Records a test start if the limit allows it.
+ public bool TryRegisterTest()
+ {
+ lock (_gate)
+ {
+ Prune();
+ if (_state.RecentTests.Count >= MaxTestsPerDay)
+ {
+ return false;
+ }
+
+ _state.RecentTests.Add(_time.GetUtcNow());
+ Save();
+ return true;
+ }
+ }
+
+ private void Prune()
+ {
+ DateTimeOffset cutoff = _time.GetUtcNow() - Window;
+ _state.RecentTests.RemoveAll(t => t <= cutoff);
+ }
+
+ private static LocalState Load(string path)
+ {
+ try
+ {
+ if (File.Exists(path))
+ {
+ using FileStream stream = File.OpenRead(path);
+ return JsonSerializer.Deserialize(stream, LocalStateJsonContext.Default.LocalState) ?? new LocalState();
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
+ {
+ // A corrupt or unreadable file means "no consent yet": the user will simply be asked again.
+ }
+
+ return new LocalState();
+ }
+
+ private void Save()
+ {
+ try
+ {
+ string? directory = Path.GetDirectoryName(_path);
+ if (!string.IsNullOrEmpty(directory))
+ {
+ Directory.CreateDirectory(directory);
+ }
+
+ string temp = _path + ".tmp";
+ File.WriteAllText(temp, JsonSerializer.Serialize(_state, LocalStateJsonContext.Default.LocalState));
+ File.Move(temp, _path, overwrite: true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // Best effort: the in-memory state still applies for this session.
+ }
+ }
+}
diff --git a/NetSpeed.Core/Measurement/Stats.cs b/NetSpeed.Core/Measurement/Stats.cs
new file mode 100644
index 0000000..cfbc173
--- /dev/null
+++ b/NetSpeed.Core/Measurement/Stats.cs
@@ -0,0 +1,79 @@
+namespace NetSpeed.Core.Measurement;
+
+public static class LatencyStats
+{
+ public static double? Median(IReadOnlyCollection values)
+ {
+ ArgumentNullException.ThrowIfNull(values);
+ if (values.Count == 0)
+ {
+ return null;
+ }
+
+ double[] sorted = [.. values];
+ Array.Sort(sorted);
+ int mid = sorted.Length / 2;
+ return sorted.Length % 2 == 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2d;
+ }
+
+ ///
+ /// Jitter as the mean absolute difference between consecutive samples (the definition
+ /// used by most consumer speed tests). Needs at least two samples.
+ ///
+ public static double? Jitter(IReadOnlyList samples)
+ {
+ ArgumentNullException.ThrowIfNull(samples);
+ if (samples.Count < 2)
+ {
+ return null;
+ }
+
+ double sum = 0;
+ for (int i = 1; i < samples.Count; i++)
+ {
+ sum += Math.Abs(samples[i] - samples[i - 1]);
+ }
+
+ return sum / (samples.Count - 1);
+ }
+}
+
+public static class ServerRanker
+{
+ ///
+ /// Orders items by measured RTT (ascending). Items without a measurement keep their
+ /// original (Locate) order after all measured ones. The sort is stable.
+ ///
+ public static IReadOnlyList Rank(IReadOnlyList items, IReadOnlyList rttMs)
+ {
+ ArgumentNullException.ThrowIfNull(items);
+ ArgumentNullException.ThrowIfNull(rttMs);
+ if (items.Count != rttMs.Count)
+ {
+ throw new ArgumentException("Items and RTTs must have the same length.", nameof(rttMs));
+ }
+
+ return [.. Enumerable.Range(0, items.Count)
+ .OrderBy(i => rttMs[i].HasValue ? 0 : 1)
+ .ThenBy(i => rttMs[i] ?? 0)
+ .ThenBy(i => i)
+ .Select(i => items[i])];
+ }
+}
+
+public static class MessageSizer
+{
+ ///
+ /// Upload message scaling from the ndt7 spec appendix (also used by MSAK): double the
+ /// message when it is no larger than 1/16 of the bytes queued so far, up to .
+ ///
+ public static int Next(int current, long totalQueued, int max)
+ {
+ if (current >= max)
+ {
+ return max;
+ }
+
+ return current <= totalQueued / 16 ? Math.Min(current * 2, max) : current;
+ }
+}
diff --git a/NetSpeed.Core/Measurement/TcpPinger.cs b/NetSpeed.Core/Measurement/TcpPinger.cs
new file mode 100644
index 0000000..54a97df
--- /dev/null
+++ b/NetSpeed.Core/Measurement/TcpPinger.cs
@@ -0,0 +1,72 @@
+using System.Diagnostics;
+using System.Net;
+using System.Net.Sockets;
+
+namespace NetSpeed.Core.Measurement;
+
+///
+/// Measures round-trip time as the duration of a TCP handshake (SYN → SYN/ACK) to the test
+/// server's HTTPS port. No payload is sent; the socket is closed right after connecting.
+/// DNS is resolved once beforehand so it does not count.
+///
+public static class TcpPinger
+{
+ public static async Task ResolveAsync(string host, CancellationToken cancellationToken)
+ {
+ try
+ {
+ IPAddress[] addresses = await Dns.GetHostAddressesAsync(host, cancellationToken).ConfigureAwait(false);
+ return addresses.Length > 0 ? addresses[0] : null;
+ }
+ catch (SocketException)
+ {
+ return null;
+ }
+ }
+
+ /// RTT in milliseconds, or null if the connection failed or timed out.
+ public static async Task PingAsync(IPAddress address, int port, TimeSpan timeout, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(address);
+
+ using Socket socket = new(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
+ using CancellationTokenSource timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeoutCts.CancelAfter(timeout);
+
+ long start = Stopwatch.GetTimestamp();
+ try
+ {
+ await socket.ConnectAsync(new IPEndPoint(address, port), timeoutCts.Token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ return null;
+ }
+ catch (SocketException)
+ {
+ return null;
+ }
+
+ return Stopwatch.GetElapsedTime(start).TotalMilliseconds;
+ }
+
+ /// Runs sequential pings spaced by .
+ public static async Task> PingSeriesAsync(IPAddress address, int port, int count, TimeSpan interval, CancellationToken cancellationToken)
+ {
+ List samples = [];
+ for (int i = 0; i < count; i++)
+ {
+ if (i > 0)
+ {
+ await Task.Delay(interval, cancellationToken).ConfigureAwait(false);
+ }
+
+ if (await PingAsync(address, port, TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false) is double rtt)
+ {
+ samples.Add(rtt);
+ }
+ }
+
+ return samples;
+ }
+}
diff --git a/NetSpeed.Core/Measurement/ThroughputTracker.cs b/NetSpeed.Core/Measurement/ThroughputTracker.cs
new file mode 100644
index 0000000..6bae187
--- /dev/null
+++ b/NetSpeed.Core/Measurement/ThroughputTracker.cs
@@ -0,0 +1,143 @@
+namespace NetSpeed.Core.Measurement;
+
+///
+/// Turns cumulative byte counters sampled over time into throughput figures.
+/// Samples are (seconds since the phase started, total bytes so far); the implicit first
+/// sample is (0, 0).
+///
+public sealed class ThroughputTracker
+{
+ /// Minimum steady-state window; shorter windows fall back to the full average.
+ public const double MinSteadySeconds = 1.0;
+
+ private readonly List _samples = [];
+ private readonly double _warmupSeconds;
+
+ ///
+ /// Initial part of the phase excluded from (TCP slow start and
+ /// stream ramp-up).
+ ///
+ public ThroughputTracker(double warmupSeconds)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegative(warmupSeconds);
+ _warmupSeconds = warmupSeconds;
+ }
+
+ public int Count => _samples.Count;
+
+ public long TotalBytes => _samples.Count == 0 ? 0 : _samples[^1].Bytes;
+
+ public double ElapsedSeconds => _samples.Count == 0 ? 0 : _samples[^1].Seconds;
+
+ ///
+ /// Average over the whole phase, ramp-up included. The phase ends at the first sample that
+ /// reached the final byte count: idle time spent waiting for the close handshake is excluded.
+ ///
+ public double AverageMbps
+ {
+ get
+ {
+ if (_samples.Count == 0)
+ {
+ return 0;
+ }
+
+ Sample end = _samples[EndIndex()];
+ return Mbps(end.Bytes, end.Seconds);
+ }
+ }
+
+ ///
+ /// Throughput after the warm-up: bytes moved between the first sample at or after the
+ /// warm-up and the end of data transfer, divided by that time. Falls back to
+ /// when less than remain.
+ ///
+ public double SteadyMbps
+ {
+ get
+ {
+ if (_samples.Count < 2)
+ {
+ return AverageMbps;
+ }
+
+ Sample last = _samples[EndIndex()];
+ int start = _samples.FindIndex(s => s.Seconds >= _warmupSeconds);
+ if (start < 0 || last.Seconds - _samples[start].Seconds < MinSteadySeconds)
+ {
+ return AverageMbps;
+ }
+
+ Sample first = _samples[start];
+ return Mbps(last.Bytes - first.Bytes, last.Seconds - first.Seconds);
+ }
+ }
+
+ /// Adds a sample. Non-increasing times are ignored; byte counters never go backwards.
+ public void Add(double seconds, long totalBytes)
+ {
+ if (double.IsNaN(seconds) || seconds <= 0)
+ {
+ return;
+ }
+
+ if (_samples.Count > 0)
+ {
+ Sample last = _samples[^1];
+ if (seconds <= last.Seconds)
+ {
+ return;
+ }
+
+ totalBytes = Math.Max(totalBytes, last.Bytes);
+ }
+
+ _samples.Add(new Sample(seconds, Math.Max(0, totalBytes)));
+ }
+
+ /// Throughput over the most recent .
+ public double CurrentMbps(double windowSeconds = 1.0)
+ {
+ if (_samples.Count == 0)
+ {
+ return 0;
+ }
+
+ Sample last = _samples[^1];
+ Sample reference = new(0, 0);
+ for (int i = _samples.Count - 2; i >= 0; i--)
+ {
+ reference = _samples[i];
+ if (last.Seconds - reference.Seconds >= windowSeconds)
+ {
+ break;
+ }
+
+ if (i == 0)
+ {
+ // Not enough history yet: measure from the start of the phase.
+ reference = new Sample(0, 0);
+ }
+ }
+
+ return Mbps(last.Bytes - reference.Bytes, last.Seconds - reference.Seconds);
+ }
+
+ /// Index of the first sample that reached the final byte count (end of data flow).
+ private int EndIndex()
+ {
+ long total = _samples[^1].Bytes;
+ int index = _samples.Count - 1;
+ while (index > 0 && _samples[index - 1].Bytes == total)
+ {
+ index--;
+ }
+
+ return index;
+ }
+
+ public static double Mbps(long bytes, double seconds) =>
+ seconds <= 0 ? 0 : bytes * 8d / seconds / 1_000_000d;
+
+ private readonly record struct Sample(double Seconds, long Bytes);
+}
diff --git a/NetSpeed.Core/Mlab/JsonModels.cs b/NetSpeed.Core/Mlab/JsonModels.cs
new file mode 100644
index 0000000..b910fb9
--- /dev/null
+++ b/NetSpeed.Core/Mlab/JsonModels.cs
@@ -0,0 +1,128 @@
+using System.Text.Json.Serialization;
+
+namespace NetSpeed.Core.Mlab;
+
+// ---- Locate v2 ----------------------------------------------------------
+
+public sealed class LocateResponse
+{
+ [JsonPropertyName("results")]
+ public List? Results { get; set; }
+}
+
+public sealed class LocateResult
+{
+ [JsonPropertyName("machine")]
+ public string? Machine { get; set; }
+
+ [JsonPropertyName("hostname")]
+ public string? Hostname { get; set; }
+
+ [JsonPropertyName("location")]
+ public LocateLocation? Location { get; set; }
+
+ [JsonPropertyName("urls")]
+ public Dictionary? Urls { get; set; }
+}
+
+public sealed class LocateLocation
+{
+ [JsonPropertyName("city")]
+ public string? City { get; set; }
+
+ [JsonPropertyName("country")]
+ public string? Country { get; set; }
+}
+
+// ---- Server measurement messages -----------------------------------------
+
+/// TCP_INFO subset shared by ndt7 and MSAK (field names match the wire JSON).
+public sealed class TcpInfoMessage
+{
+ public long? BusyTime { get; set; }
+
+ public long? BytesAcked { get; set; }
+
+ public long? BytesReceived { get; set; }
+
+ public long? BytesSent { get; set; }
+
+ public long? BytesRetrans { get; set; }
+
+ public long? ElapsedTime { get; set; }
+
+ /// Minimum RTT seen by the server kernel, microseconds.
+ public long? MinRTT { get; set; }
+
+ /// Smoothed RTT, microseconds.
+ public long? RTT { get; set; }
+
+ public long? RTTVar { get; set; }
+}
+
+/// MSAK throughput1 WireMeasurement (pkg/throughput1/model).
+public sealed class MsakWireMeasurement
+{
+ public string? CC { get; set; }
+
+ public string? UUID { get; set; }
+
+ public string? LocalAddr { get; set; }
+
+ /// Client address as seen by the server ("ip:port").
+ public string? RemoteAddr { get; set; }
+
+ public MsakByteCounters? Application { get; set; }
+
+ public MsakByteCounters? Network { get; set; }
+
+ /// Microseconds since the stream started.
+ public long? ElapsedTime { get; set; }
+
+ public TcpInfoMessage? TCPInfo { get; set; }
+}
+
+public sealed class MsakByteCounters
+{
+ public long? BytesSent { get; set; }
+
+ public long? BytesReceived { get; set; }
+}
+
+/// ndt7 measurement message (spec v0.11.0, "Measurement message").
+public sealed class Ndt7Measurement
+{
+ public Ndt7AppInfo? AppInfo { get; set; }
+
+ public Ndt7ConnectionInfo? ConnectionInfo { get; set; }
+
+ public string? Origin { get; set; }
+
+ public string? Test { get; set; }
+
+ public TcpInfoMessage? TCPInfo { get; set; }
+}
+
+public sealed class Ndt7AppInfo
+{
+ public long? ElapsedTime { get; set; }
+
+ public long? NumBytes { get; set; }
+}
+
+public sealed class Ndt7ConnectionInfo
+{
+ public string? Client { get; set; }
+
+ public string? Server { get; set; }
+
+ public string? UUID { get; set; }
+}
+
+[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true)]
+[JsonSerializable(typeof(LocateResponse))]
+[JsonSerializable(typeof(MsakWireMeasurement))]
+[JsonSerializable(typeof(Ndt7Measurement))]
+internal sealed partial class MlabJsonContext : JsonSerializerContext
+{
+}
diff --git a/NetSpeed.Core/Mlab/Locate.cs b/NetSpeed.Core/Mlab/Locate.cs
new file mode 100644
index 0000000..2422e10
--- /dev/null
+++ b/NetSpeed.Core/Mlab/Locate.cs
@@ -0,0 +1,125 @@
+using System.Net;
+using System.Text.Json;
+
+namespace NetSpeed.Core.Mlab;
+
+/// One server returned by Locate v2, with ready-to-use, token-bearing URLs.
+public sealed record MlabTarget(
+ string Machine,
+ string Hostname,
+ string? City,
+ string? Country,
+ Uri DownloadUrl,
+ Uri UploadUrl);
+
+/// Parses Locate v2 "nearest" answers.
+public static class LocateParser
+{
+ ///
+ /// Returns the usable targets in Locate order. Results lacking either URL, or with a
+ /// non-wss URL, are skipped.
+ ///
+ public static IReadOnlyList Parse(string json, MlabProtocol protocol)
+ {
+ ArgumentNullException.ThrowIfNull(protocol);
+
+ LocateResponse? response;
+ try
+ {
+ response = JsonSerializer.Deserialize(json, MlabJsonContext.Default.LocateResponse);
+ }
+ catch (JsonException ex)
+ {
+ throw new SpeedTestException(SpeedTestErrorKind.LocateFailed, "M-Lab Locate returned invalid JSON.", ex);
+ }
+
+ List targets = [];
+ foreach (LocateResult result in response?.Results ?? [])
+ {
+ if (result.Urls is null
+ || !result.Urls.TryGetValue(protocol.DownloadKey, out string? download)
+ || !result.Urls.TryGetValue(protocol.UploadKey, out string? upload)
+ || !Uri.TryCreate(download, UriKind.Absolute, out Uri? downloadUri)
+ || !Uri.TryCreate(upload, UriKind.Absolute, out Uri? uploadUri)
+ || downloadUri.Scheme != "wss"
+ || uploadUri.Scheme != "wss")
+ {
+ continue;
+ }
+
+ string host = !string.IsNullOrWhiteSpace(result.Hostname) ? result.Hostname : downloadUri.Host;
+ string machine = !string.IsNullOrWhiteSpace(result.Machine) ? result.Machine : host;
+ targets.Add(new MlabTarget(machine, host, result.Location?.City, result.Location?.Country, downloadUri, uploadUri));
+ }
+
+ return targets;
+ }
+}
+
+/// Minimal Locate v2 client (https://locate.measurementlab.net/v2/nearest/{service}).
+public sealed class LocateClient
+{
+ public static readonly Uri BaseUri = new("https://locate.measurementlab.net/v2/nearest/");
+
+ private readonly HttpClient _http;
+ private readonly string _userAgent;
+
+ public LocateClient(HttpClient http, string userAgent)
+ {
+ _http = http ?? throw new ArgumentNullException(nameof(http));
+ _userAgent = userAgent;
+ }
+
+ public async Task> NearestAsync(MlabProtocol protocol, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(protocol);
+
+ using HttpRequestMessage request = new(HttpMethod.Get, new Uri(BaseUri, protocol.LocateService));
+ request.Headers.TryAddWithoutValidation("User-Agent", _userAgent);
+ request.Headers.TryAddWithoutValidation("Accept", "application/json");
+
+ HttpResponseMessage response;
+ try
+ {
+ response = await _http.SendAsync(request, cancellationToken).ConfigureAwait(false);
+ }
+ catch (HttpRequestException ex)
+ {
+ throw new SpeedTestException(SpeedTestErrorKind.Network, "Could not reach M-Lab (locate.measurementlab.net). Check your Internet connection.", ex);
+ }
+ catch (TaskCanceledException ex) when (!cancellationToken.IsCancellationRequested)
+ {
+ throw new SpeedTestException(SpeedTestErrorKind.Timeout, "M-Lab Locate did not answer in time.", ex);
+ }
+
+ using (response)
+ {
+ return await InterpretAsync(response, protocol, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ internal static async Task> InterpretAsync(HttpResponseMessage response, MlabProtocol protocol, CancellationToken cancellationToken)
+ {
+ // ndt7 spec, "Server discovery": 200 = success, 204 = no capacity, anything else = failure.
+ if (response.StatusCode == HttpStatusCode.NoContent)
+ {
+ throw new SpeedTestException(SpeedTestErrorKind.NoCapacity, "M-Lab has no free test capacity right now. Please try again in a few minutes.");
+ }
+
+ if (response.StatusCode != HttpStatusCode.OK)
+ {
+ throw new SpeedTestException(
+ SpeedTestErrorKind.LocateFailed,
+ $"M-Lab Locate answered HTTP {(int)response.StatusCode} for {protocol.LocateService}.");
+ }
+
+ string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
+ IReadOnlyList targets = LocateParser.Parse(json, protocol);
+ if (targets.Count == 0)
+ {
+ throw new SpeedTestException(SpeedTestErrorKind.LocateFailed, $"M-Lab Locate returned no usable {protocol.DisplayName} server.");
+ }
+
+ return targets;
+ }
+}
diff --git a/NetSpeed.Core/Mlab/MeasurementParser.cs b/NetSpeed.Core/Mlab/MeasurementParser.cs
new file mode 100644
index 0000000..ba1c53e
--- /dev/null
+++ b/NetSpeed.Core/Mlab/MeasurementParser.cs
@@ -0,0 +1,97 @@
+using System.Text.Json;
+
+namespace NetSpeed.Core.Mlab;
+
+/// Server measurement normalised across ndt7 and MSAK.
+/// Application-level bytes moved in the test direction, as counted by the server.
+/// Server-side elapsed time.
+/// TCP_INFO MinRTT.
+/// TCP_INFO smoothed RTT.
+/// Client address as seen by the server, without port.
+/// M-Lab measurement UUID, when present.
+public readonly record struct ServerMeasurement(
+ long? AppBytes,
+ long? ElapsedMicroseconds,
+ long? MinRttMicroseconds,
+ long? RttMicroseconds,
+ string? ClientAddress,
+ string? Uuid);
+
+public static class MeasurementParser
+{
+ /// Parses a textual WebSocket message. Returns false for malformed input.
+ public static bool TryParse(MlabProtocolKind kind, TestDirection direction, ReadOnlySpan utf8Json, out ServerMeasurement measurement)
+ {
+ measurement = default;
+ try
+ {
+ if (kind == MlabProtocolKind.Msak)
+ {
+ MsakWireMeasurement? m = JsonSerializer.Deserialize(utf8Json, MlabJsonContext.Default.MsakWireMeasurement);
+ if (m is null)
+ {
+ return false;
+ }
+
+ // Download: the server is the sender. Upload: the server is the receiver.
+ long? appBytes = direction == TestDirection.Download ? m.Application?.BytesSent : m.Application?.BytesReceived;
+ measurement = new ServerMeasurement(
+ appBytes,
+ m.ElapsedTime,
+ m.TCPInfo?.MinRTT,
+ m.TCPInfo?.RTT,
+ AddressHelper.StripPort(m.RemoteAddr),
+ m.UUID);
+ return true;
+ }
+
+ Ndt7Measurement? n = JsonSerializer.Deserialize(utf8Json, MlabJsonContext.Default.Ndt7Measurement);
+ if (n is null)
+ {
+ return false;
+ }
+
+ measurement = new ServerMeasurement(
+ n.AppInfo?.NumBytes,
+ n.AppInfo?.ElapsedTime ?? n.TCPInfo?.ElapsedTime,
+ n.TCPInfo?.MinRTT,
+ n.TCPInfo?.RTT,
+ AddressHelper.StripPort(n.ConnectionInfo?.Client),
+ n.ConnectionInfo?.UUID);
+ return true;
+ }
+ catch (JsonException)
+ {
+ return false;
+ }
+ }
+}
+
+public static class AddressHelper
+{
+ /// "1.2.3.4:5678" → "1.2.3.4"; "[2001:db8::1]:443" → "2001:db8::1".
+ public static string? StripPort(string? endpoint)
+ {
+ if (string.IsNullOrWhiteSpace(endpoint))
+ {
+ return null;
+ }
+
+ string value = endpoint.Trim();
+ if (value.StartsWith('['))
+ {
+ int close = value.IndexOf(']', StringComparison.Ordinal);
+ return close > 1 ? value[1..close] : value;
+ }
+
+ int colon = value.LastIndexOf(':');
+
+ // More than one colon without brackets: a bare IPv6 address, leave it alone.
+ if (colon > 0 && value.IndexOf(':', StringComparison.Ordinal) == colon)
+ {
+ return value[..colon];
+ }
+
+ return value;
+ }
+}
diff --git a/NetSpeed.Core/Mlab/MlabEngine.cs b/NetSpeed.Core/Mlab/MlabEngine.cs
new file mode 100644
index 0000000..0e4fd66
--- /dev/null
+++ b/NetSpeed.Core/Mlab/MlabEngine.cs
@@ -0,0 +1,209 @@
+using System.Globalization;
+using System.Net;
+using System.Runtime.InteropServices;
+using NetSpeed.Core.Measurement;
+
+namespace NetSpeed.Core.Mlab;
+
+public sealed class MlabEngineOptions
+{
+ /// Identifies the client to M-Lab (client_name query parameter and User-Agent).
+ public string ClientName { get; init; } = "netspeed-cmdpal";
+
+ public string ClientVersion { get; init; } = "0.0.0";
+
+ /// Parallel TCP streams for MSAK. ndt7 always uses one.
+ public int Streams { get; init; } = 4;
+
+ /// Duration of each of the download and upload phases.
+ public TimeSpan PhaseDuration { get; init; } = TimeSpan.FromSeconds(10);
+
+ /// Initial seconds of each phase excluded from the headline (steady-state) value.
+ public double WarmupSeconds { get; init; } = 2.0;
+
+ public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10);
+
+ /// TCP-handshake samples taken before the test for idle latency and jitter.
+ public int IdlePingCount { get; init; } = 10;
+
+ public string UserAgent => $"{ClientName}/{ClientVersion} (+https://github.com/mrgenty/NetSpeed-CmdPal)";
+}
+
+///
+/// M-Lab engine: Locate v2 → MSAK throughput1 (multi-stream); falls back to ndt7 when MSAK has
+/// no capacity or every MSAK server refuses the connection.
+///
+public sealed class MlabEngine : ISpeedEngine
+{
+ private const int HttpsPort = 443;
+ private const string LibraryName = "netspeed-core";
+
+ private readonly LocateClient _locate;
+ private readonly MlabEngineOptions _options;
+
+ public MlabEngine(HttpClient http, MlabEngineOptions options)
+ {
+ _options = options ?? throw new ArgumentNullException(nameof(options));
+ _locate = new LocateClient(http, options.UserAgent);
+ }
+
+ public string Name => "M-Lab";
+
+ public async Task RunAsync(IProgress? progress, CancellationToken cancellationToken)
+ {
+ SpeedTestException? lastError = null;
+ foreach (MlabProtocol protocol in new[] { MlabProtocol.Msak, MlabProtocol.Ndt7 })
+ {
+ progress?.Report(new SpeedProgress(SpeedPhase.Locating, 0.01, null, $"Finding the nearest M-Lab server ({protocol.DisplayName})…"));
+
+ IReadOnlyList targets;
+ try
+ {
+ targets = await _locate.NearestAsync(protocol, cancellationToken).ConfigureAwait(false);
+ }
+ catch (SpeedTestException ex) when (ex.Kind is SpeedTestErrorKind.NoCapacity or SpeedTestErrorKind.LocateFailed)
+ {
+ lastError = ex;
+ continue;
+ }
+
+ progress?.Report(new SpeedProgress(SpeedPhase.Locating, 0.03, null, "Picking the closest server…"));
+ foreach ((MlabTarget target, IPAddress? address) in await RankAsync(targets, cancellationToken).ConfigureAwait(false))
+ {
+ try
+ {
+ return await RunOnTargetAsync(protocol, target, address, progress, cancellationToken).ConfigureAwait(false);
+ }
+ catch (ServerUnavailableException ex)
+ {
+ lastError = new SpeedTestException(SpeedTestErrorKind.AllServersRejected, ex.Message, ex);
+ }
+ }
+ }
+
+ throw lastError is { Kind: SpeedTestErrorKind.AllServersRejected }
+ ? new SpeedTestException(SpeedTestErrorKind.AllServersRejected, "All nearby M-Lab servers are busy or refused the test. Please try again later.", lastError)
+ : lastError ?? new SpeedTestException(SpeedTestErrorKind.LocateFailed, "No M-Lab server available.");
+ }
+
+ internal static IReadOnlyList> BuildQuery(MlabProtocol protocol, MlabEngineOptions options, int streams)
+ {
+ List> query = [];
+ if (protocol.Kind == MlabProtocolKind.Msak)
+ {
+ // Required by msak-server; duration is in milliseconds.
+ query.Add(new("streams", streams.ToString(CultureInfo.InvariantCulture)));
+ query.Add(new("duration", ((long)options.PhaseDuration.TotalMilliseconds).ToString(CultureInfo.InvariantCulture)));
+ }
+
+ query.Add(new("client_name", options.ClientName));
+ query.Add(new("client_version", options.ClientVersion));
+ query.Add(new("client_library_name", LibraryName));
+ query.Add(new("client_library_version", options.ClientVersion));
+ query.Add(new("client_os", OperatingSystem.IsWindows() ? "windows" : RuntimeInformation.OSDescription));
+ query.Add(new("client_arch", RuntimeInformation.OSArchitecture.ToString().ToLowerInvariant()));
+ return query;
+ }
+
+ private static async Task> RankAsync(IReadOnlyList targets, CancellationToken cancellationToken)
+ {
+ (MlabTarget Target, IPAddress? Address, double? Rtt)[] probes = await Task.WhenAll(targets.Select(async target =>
+ {
+ IPAddress? address = await TcpPinger.ResolveAsync(target.Hostname, cancellationToken).ConfigureAwait(false);
+ double? rtt = null;
+ if (address is not null)
+ {
+ List samples = await TcpPinger.PingSeriesAsync(address, HttpsPort, 3, TimeSpan.FromMilliseconds(50), cancellationToken).ConfigureAwait(false);
+ rtt = LatencyStats.Median(samples);
+ }
+
+ return (target, address, rtt);
+ })).ConfigureAwait(false);
+
+ return ServerRanker.Rank(
+ [.. probes.Select(p => (p.Target, p.Address))],
+ [.. probes.Select(p => p.Rtt)]);
+ }
+
+ private async Task RunOnTargetAsync(MlabProtocol protocol, MlabTarget target, IPAddress? address, IProgress? progress, CancellationToken cancellationToken)
+ {
+ string where = FormatPlace(target);
+ int streams = protocol.SupportsMultipleStreams ? _options.Streams : 1;
+ string detail = $"{protocol.DisplayName} • {streams} stream{(streams == 1 ? string.Empty : "s")} • {where}";
+
+ progress?.Report(new SpeedProgress(SpeedPhase.Latency, 0.05, null, $"Measuring idle latency • {where}"));
+ List idle = address is null
+ ? []
+ : await TcpPinger.PingSeriesAsync(address, HttpsPort, _options.IdlePingCount, TimeSpan.FromMilliseconds(100), cancellationToken).ConfigureAwait(false);
+
+ IReadOnlyList> query = BuildQuery(protocol, _options, streams);
+
+ PhaseResult download = await PhaseRunner.RunAsync(
+ Phase(protocol, TestDirection.Download, target.DownloadUrl, streams, query, address),
+ (fraction, mbps) => progress?.Report(new SpeedProgress(SpeedPhase.Download, 0.10 + (0.45 * fraction), mbps, detail)),
+ cancellationToken).ConfigureAwait(false);
+
+ PhaseResult upload;
+ try
+ {
+ upload = await PhaseRunner.RunAsync(
+ Phase(protocol, TestDirection.Upload, target.UploadUrl, streams, query, address),
+ (fraction, mbps) => progress?.Report(new SpeedProgress(SpeedPhase.Upload, 0.55 + (0.45 * fraction), mbps, detail)),
+ cancellationToken).ConfigureAwait(false);
+ }
+ catch (ServerUnavailableException ex)
+ {
+ // Download already ran on this server: do not silently switch servers mid-test.
+ throw new SpeedTestException(SpeedTestErrorKind.Protocol, "The upload test could not start: " + ex.Message, ex);
+ }
+
+ bool pinged = idle.Count >= 3;
+ double? idleLatency = pinged ? LatencyStats.Median(idle) : download.ServerMinRttMs;
+ double? downLoaded = download.LoadedPingsMs.Count >= 3 ? LatencyStats.Median(download.LoadedPingsMs) : LatencyStats.Median(download.ServerRttMs);
+ double? upLoaded = upload.LoadedPingsMs.Count >= 3 ? LatencyStats.Median(upload.LoadedPingsMs) : null;
+
+ return new SpeedResult
+ {
+ EngineName = Name,
+ Protocol = protocol.DisplayName,
+ Timestamp = DateTimeOffset.Now,
+ DownloadMbps = download.SteadyMbps,
+ DownloadAverageMbps = download.AverageMbps,
+ UploadMbps = upload.SteadyMbps,
+ UploadAverageMbps = upload.AverageMbps,
+ IdleLatencyMs = idleLatency,
+ JitterMs = pinged ? LatencyStats.Jitter(idle) : null,
+ DownloadLoadedLatencyMs = downLoaded,
+ UploadLoadedLatencyMs = upLoaded,
+ LatencyMethod = pinged ? "TCP handshake to the test server" : "Server-side TCP_INFO RTT (handshake probes unavailable)",
+ ServerMachine = target.Machine,
+ ServerCity = target.City,
+ ServerCountry = target.Country,
+ ClientAddress = download.ClientAddress ?? upload.ClientAddress,
+ BytesReceived = download.Bytes,
+ BytesSent = upload.Bytes,
+ Streams = Math.Max(download.StreamsConnected, upload.StreamsConnected),
+ };
+ }
+
+ private PhaseOptions Phase(MlabProtocol protocol, TestDirection direction, Uri url, int streams, IReadOnlyList> query, IPAddress? address) => new()
+ {
+ Protocol = protocol,
+ Direction = direction,
+ Url = url,
+ Streams = streams,
+ Duration = _options.PhaseDuration,
+ WarmupSeconds = _options.WarmupSeconds,
+ UserAgent = _options.UserAgent,
+ Query = query,
+ ConnectTimeout = _options.ConnectTimeout,
+ PingAddress = address,
+ PingPort = HttpsPort,
+ };
+
+ private static string FormatPlace(MlabTarget target)
+ {
+ string place = string.Join(", ", new[] { target.City, target.Country }.Where(p => !string.IsNullOrWhiteSpace(p)));
+ return string.IsNullOrEmpty(place) ? target.Machine : place;
+ }
+}
diff --git a/NetSpeed.Core/Mlab/MlabProtocol.cs b/NetSpeed.Core/Mlab/MlabProtocol.cs
new file mode 100644
index 0000000..591d2a4
--- /dev/null
+++ b/NetSpeed.Core/Mlab/MlabProtocol.cs
@@ -0,0 +1,88 @@
+namespace NetSpeed.Core.Mlab;
+
+public enum MlabProtocolKind
+{
+ /// MSAK throughput1: multi-stream, WebSocket over TLS.
+ Msak,
+
+ /// ndt7: single stream, WebSocket over TLS.
+ Ndt7,
+}
+
+public enum TestDirection
+{
+ Download,
+ Upload,
+}
+
+/// Static description of an M-Lab throughput protocol.
+public sealed class MlabProtocol
+{
+ ///
+ /// MSAK throughput1. Values from github.com/m-lab/msak pkg/throughput1/spec/spec.go
+ /// and the Locate v2 answer for "msak/throughput1".
+ ///
+ public static readonly MlabProtocol Msak = new(
+ MlabProtocolKind.Msak,
+ displayName: "MSAK throughput1",
+ locateService: "msak/throughput1",
+ downloadKey: "wss:///throughput/v1/download",
+ uploadKey: "wss:///throughput/v1/upload",
+ subProtocol: "net.measurementlab.throughput.v1",
+ maxMessageSize: 1 << 20);
+
+ /// ndt7, from github.com/m-lab/ndt-server spec/ndt7-protocol.md (v0.11.0).
+ public static readonly MlabProtocol Ndt7 = new(
+ MlabProtocolKind.Ndt7,
+ displayName: "ndt7",
+ locateService: "ndt/ndt7",
+ downloadKey: "wss:///ndt/v7/download",
+ uploadKey: "wss:///ndt/v7/upload",
+ subProtocol: "net.measurementlab.ndt.v7",
+ maxMessageSize: 1 << 20);
+
+ private MlabProtocol(
+ MlabProtocolKind kind,
+ string displayName,
+ string locateService,
+ string downloadKey,
+ string uploadKey,
+ string subProtocol,
+ int maxMessageSize)
+ {
+ Kind = kind;
+ DisplayName = displayName;
+ LocateService = locateService;
+ DownloadKey = downloadKey;
+ UploadKey = uploadKey;
+ SubProtocol = subProtocol;
+ MaxMessageSize = maxMessageSize;
+ }
+
+ public MlabProtocolKind Kind { get; }
+
+ public string DisplayName { get; }
+
+ /// Service path appended to https://locate.measurementlab.net/v2/nearest/.
+ public string LocateService { get; }
+
+ /// Key of the download URL in the Locate "urls" map.
+ public string DownloadKey { get; }
+
+ public string UploadKey { get; }
+
+ /// Value for Sec-WebSocket-Protocol.
+ public string SubProtocol { get; }
+
+ /// Initial upload binary message size (ndt7 spec: 1 << 13).
+ public int InitialMessageSize { get; } = 1 << 13;
+
+ ///
+ /// Upper bound for upload messages. ndt7 allows up to 1 << 24; MSAK uses 1 << 20
+ /// (spec.MaxScaledMessageSize). 1 MiB is used for both.
+ ///
+ public int MaxMessageSize { get; }
+
+ /// True when the protocol supports several parallel TCP streams per test.
+ public bool SupportsMultipleStreams => Kind == MlabProtocolKind.Msak;
+}
diff --git a/NetSpeed.Core/Mlab/PhaseRunner.cs b/NetSpeed.Core/Mlab/PhaseRunner.cs
new file mode 100644
index 0000000..6d8ccac
--- /dev/null
+++ b/NetSpeed.Core/Mlab/PhaseRunner.cs
@@ -0,0 +1,479 @@
+using System.Buffers;
+using System.Diagnostics;
+using System.Net;
+using System.Net.WebSockets;
+using System.Security.Cryptography;
+using NetSpeed.Core.Measurement;
+
+namespace NetSpeed.Core.Mlab;
+
+/// Thrown when no stream could connect to a server, so the caller can try the next one.
+internal sealed class ServerUnavailableException : Exception
+{
+ public ServerUnavailableException()
+ {
+ }
+
+ public ServerUnavailableException(string message)
+ : base(message)
+ {
+ }
+
+ public ServerUnavailableException(string message, Exception? innerException)
+ : base(message, innerException)
+ {
+ }
+}
+
+internal sealed class PhaseOptions
+{
+ public required MlabProtocol Protocol { get; init; }
+
+ public required TestDirection Direction { get; init; }
+
+ public required Uri Url { get; init; }
+
+ public required int Streams { get; init; }
+
+ public required TimeSpan Duration { get; init; }
+
+ public required double WarmupSeconds { get; init; }
+
+ public required string UserAgent { get; init; }
+
+ public required IReadOnlyList> Query { get; init; }
+
+ public required TimeSpan ConnectTimeout { get; init; }
+
+ /// When set, TCP-handshake pings run during the phase to measure loaded latency.
+ public IPAddress? PingAddress { get; init; }
+
+ public int PingPort { get; init; } = 443;
+}
+
+internal sealed class PhaseResult
+{
+ public double SteadyMbps { get; init; }
+
+ public double AverageMbps { get; init; }
+
+ public long Bytes { get; init; }
+
+ public int StreamsConnected { get; init; }
+
+ /// TCP-handshake RTTs (ms) measured during the phase, after the first second.
+ public required List LoadedPingsMs { get; init; }
+
+ /// Server-side smoothed RTT samples (ms) from TCP_INFO.
+ public required List ServerRttMs { get; init; }
+
+ public double? ServerMinRttMs { get; init; }
+
+ public string? ClientAddress { get; init; }
+
+ public required List Uuids { get; init; }
+}
+
+/// Runs one download or upload phase over one or more WebSocket streams.
+internal static class PhaseRunner
+{
+ private const int ReceiveBufferSize = 1 << 20;
+ private const int MaxTextMessageSize = 1 << 20;
+ private static readonly TimeSpan SampleInterval = TimeSpan.FromMilliseconds(100);
+ private static readonly TimeSpan PingInterval = TimeSpan.FromMilliseconds(250);
+ private static readonly TimeSpan GracePeriod = TimeSpan.FromSeconds(3);
+ private static readonly byte[] Payload = CreatePayload();
+
+ /// Called about every 100 ms with (phase fraction 0..1, current Mbps).
+ public static async Task RunAsync(PhaseOptions options, Action? onSample, CancellationToken cancellationToken)
+ {
+ Uri url = TestUriBuilder.AddQuery(options.Url, options.Query);
+ int streamCount = options.Protocol.SupportsMultipleStreams ? Math.Max(1, options.Streams) : 1;
+
+ // The phase clock starts when the first stream connects. Each stream starts consuming
+ // data as soon as its own handshake completes: the server starts its timed test at
+ // upgrade, so waiting for slower streams would distort the measurement.
+ Stopwatch clock = Stopwatch.StartNew();
+ PhaseClock phase = new(clock);
+ using CancellationTokenSource deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ deadline.CancelAfter(options.ConnectTimeout + options.Duration + GracePeriod);
+
+ StreamCounters[] counters = [.. Enumerable.Range(0, streamCount).Select(_ => new StreamCounters())];
+ Task[] streams = [.. counters.Select(c => RunStreamAsync(url, options, c, phase, deadline.Token, cancellationToken))];
+ Task all = Task.WhenAll(streams);
+
+ List<(double Seconds, double Rtt)> pings = [];
+ using CancellationTokenSource pingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ Task pingTask = options.PingAddress is null
+ ? Task.CompletedTask
+ : PingLoopAsync(options.PingAddress, options.PingPort, phase, pings, pingCts.Token);
+
+ // Upload: the server's application counters are authoritative (ndt7 spec recommends
+ // server measurements for upload); client-side counters include socket buffers.
+ ThroughputTracker clientTracker = new(options.WarmupSeconds);
+ ThroughputTracker serverTracker = new(options.WarmupSeconds);
+ bool useServer = options.Direction == TestDirection.Upload;
+
+ while (!all.IsCompleted)
+ {
+ await Task.WhenAny(all, Task.Delay(SampleInterval, cancellationToken)).ConfigureAwait(false);
+ cancellationToken.ThrowIfCancellationRequested();
+ if (phase.Started)
+ {
+ Sample(phase, counters, clientTracker, serverTracker);
+ ThroughputTracker live = useServer && serverTracker.TotalBytes > 0 ? serverTracker : clientTracker;
+ onSample?.Invoke(Math.Min(1, phase.Seconds / options.Duration.TotalSeconds), live.CurrentMbps());
+ }
+ }
+
+ Exception?[] errors = await Task.WhenAll(streams).ConfigureAwait(false);
+ await pingCts.CancelAsync().ConfigureAwait(false);
+ try
+ {
+ await pingTask.ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ }
+
+ int connected = counters.Count(c => c.Connected);
+ string what = options.Direction.ToString().ToLowerInvariant();
+ if (connected == 0)
+ {
+ Exception? first = errors.FirstOrDefault(e => e is not null);
+ throw new ServerUnavailableException($"Server refused the {what} test: {first?.Message}", first);
+ }
+
+ Sample(phase, counters, clientTracker, serverTracker);
+ bool serverReported = counters.Any(c => c.ServerMessages > 0);
+ ThroughputTracker final = useServer && serverReported ? serverTracker : clientTracker;
+
+ // Bytes the client merely queued into a socket the server then closed do not count:
+ // an upload that ended within a second without a single server measurement is empty.
+ bool emptyUpload = useServer && !serverReported && phase.Seconds < ThroughputTracker.MinSteadySeconds;
+ if (final.TotalBytes <= 0 || emptyUpload)
+ {
+ // Connected, then closed or reset before any payload: not a valid 0 Mbps result.
+ throw new ServerUnavailableException($"The server closed the {what} test before any data was transferred.");
+ }
+
+ List serverRtt = [];
+ foreach (StreamCounters c in counters)
+ {
+ serverRtt.AddRange(c.RttSnapshot());
+ }
+
+ long? minRttUs = counters.Select(c => c.MinRttMicroseconds).Where(v => v is > 0).Min();
+
+ return new PhaseResult
+ {
+ SteadyMbps = final.SteadyMbps,
+ AverageMbps = final.AverageMbps,
+ Bytes = final.TotalBytes,
+ StreamsConnected = connected,
+ LoadedPingsMs = [.. pings.Where(p => p.Seconds >= 1.0).Select(p => p.Rtt)],
+ ServerRttMs = serverRtt,
+ ServerMinRttMs = minRttUs / 1000d,
+ ClientAddress = counters.Select(c => c.ClientAddress).FirstOrDefault(a => a is not null),
+ Uuids = [.. counters.Select(c => c.Uuid).OfType().Distinct(StringComparer.Ordinal)],
+ };
+ }
+
+ private static void Sample(PhaseClock phase, StreamCounters[] counters, ThroughputTracker client, ThroughputTracker server)
+ {
+ double t = phase.Seconds;
+ client.Add(t, counters.Sum(c => Interlocked.Read(ref c.ClientBytes)));
+ server.Add(t, counters.Sum(c => Interlocked.Read(ref c.ServerAppBytes)));
+ }
+
+ /// Connects one stream and, as soon as it is up, runs its download or upload loop.
+ /// The connection error, or null when the stream connected.
+ private static async Task RunStreamAsync(Uri url, PhaseOptions options, StreamCounters counters, PhaseClock phase, CancellationToken deadline, CancellationToken userToken)
+ {
+ (ClientWebSocket? socket, Exception? error) = await ConnectAsync(url, options, userToken).ConfigureAwait(false);
+ if (socket is null)
+ {
+ return error;
+ }
+
+ using (socket)
+ {
+ counters.Connected = true;
+ phase.MarkStarted();
+ if (options.Direction == TestDirection.Download)
+ {
+ await ReceiveLoopAsync(socket, counters, options, closeOnServerClose: true, deadline, userToken).ConfigureAwait(false);
+ }
+ else
+ {
+ await UploadAsync(socket, counters, options, phase.Clock.Elapsed, phase.Clock, deadline, userToken).ConfigureAwait(false);
+ }
+ }
+
+ return null;
+ }
+
+ private static async Task<(ClientWebSocket? Socket, Exception? Error)> ConnectAsync(Uri url, PhaseOptions options, CancellationToken cancellationToken)
+ {
+ ClientWebSocket socket = new();
+ socket.Options.AddSubProtocol(options.Protocol.SubProtocol);
+ socket.Options.SetRequestHeader("User-Agent", options.UserAgent);
+ socket.Options.KeepAliveInterval = TimeSpan.Zero; // Server pings are answered automatically.
+ socket.Options.CollectHttpResponseDetails = true;
+
+ using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeout.CancelAfter(options.ConnectTimeout);
+ try
+ {
+ await socket.ConnectAsync(url, timeout.Token).ConfigureAwait(false);
+ if (!string.Equals(socket.SubProtocol, options.Protocol.SubProtocol, StringComparison.Ordinal))
+ {
+ socket.Abort();
+ socket.Dispose();
+ return (null, new WebSocketException("The server did not accept the " + options.Protocol.SubProtocol + " subprotocol."));
+ }
+
+ return (socket, null);
+ }
+ catch (Exception ex) when (ex is WebSocketException or HttpRequestException or IOException
+ || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
+ {
+ Exception error = socket.HttpStatusCode is HttpStatusCode status and not 0 and not HttpStatusCode.SwitchingProtocols
+ ? new WebSocketException($"HTTP {(int)status}", ex)
+ : ex is OperationCanceledException ? new TimeoutException("Connection timed out.", ex) : ex;
+ socket.Dispose();
+ return (null, error);
+ }
+ }
+
+ ///
+ /// Reads binary (download payload) and text (measurement) messages until the server closes,
+ /// the deadline expires, or the connection drops. Abrupt endings are tolerated, as the ndt7
+ /// spec recommends; only user cancellation is propagated.
+ ///
+ private static async Task ReceiveLoopAsync(
+ ClientWebSocket socket,
+ StreamCounters counters,
+ PhaseOptions options,
+ bool closeOnServerClose,
+ CancellationToken deadline,
+ CancellationToken userToken)
+ {
+ byte[] buffer = ArrayPool.Shared.Rent(ReceiveBufferSize);
+ ArrayBufferWriter text = new();
+ bool overflow = false;
+ try
+ {
+ while (true)
+ {
+ ValueWebSocketReceiveResult result = await socket.ReceiveAsync(buffer.AsMemory(), deadline).ConfigureAwait(false);
+ switch (result.MessageType)
+ {
+ case WebSocketMessageType.Close:
+ if (closeOnServerClose)
+ {
+ await CloseQuietlyAsync(socket).ConfigureAwait(false);
+ }
+
+ return;
+
+ case WebSocketMessageType.Binary:
+ if (options.Direction == TestDirection.Download)
+ {
+ Interlocked.Add(ref counters.ClientBytes, result.Count);
+ }
+
+ break;
+
+ case WebSocketMessageType.Text:
+ if (!overflow && text.WrittenCount + result.Count <= MaxTextMessageSize)
+ {
+ text.Write(buffer.AsSpan(0, result.Count));
+ }
+ else
+ {
+ overflow = true;
+ }
+
+ if (result.EndOfMessage)
+ {
+ if (!overflow)
+ {
+ counters.OnMeasurement(options.Protocol.Kind, options.Direction, text.WrittenSpan);
+ }
+
+ text.Clear();
+ overflow = false;
+ }
+
+ break;
+ }
+ }
+ }
+ catch (OperationCanceledException) when (!userToken.IsCancellationRequested)
+ {
+ // Deadline reached: the phase is over.
+ }
+ catch (Exception ex) when (ex is WebSocketException or IOException)
+ {
+ // Abrupt EOF/RST: keep what was measured.
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(buffer);
+ }
+ }
+
+ private static async Task UploadAsync(
+ ClientWebSocket socket,
+ StreamCounters counters,
+ PhaseOptions options,
+ TimeSpan streamStart,
+ Stopwatch clock,
+ CancellationToken deadline,
+ CancellationToken userToken)
+ {
+ // The receive loop only reads server measurements; this method owns sending, including Close.
+ Task receive = ReceiveLoopAsync(socket, counters, options, closeOnServerClose: false, deadline, userToken);
+ int size = options.Protocol.InitialMessageSize;
+ long queued = 0;
+ try
+ {
+ // Each stream uploads for the full duration from its own connection time.
+ while (socket.State == WebSocketState.Open && !receive.IsCompleted && clock.Elapsed - streamStart < options.Duration)
+ {
+ await socket.SendAsync(Payload.AsMemory(0, size), WebSocketMessageType.Binary, endOfMessage: true, deadline).ConfigureAwait(false);
+ queued += size;
+ Interlocked.Add(ref counters.ClientBytes, size);
+ size = MessageSizer.Next(size, queued, options.Protocol.MaxMessageSize);
+ }
+ }
+ catch (OperationCanceledException) when (!userToken.IsCancellationRequested)
+ {
+ }
+ catch (Exception ex) when (ex is WebSocketException or IOException)
+ {
+ }
+
+ await CloseQuietlyAsync(socket).ConfigureAwait(false);
+ await receive.ConfigureAwait(false);
+ }
+
+ private static async Task CloseQuietlyAsync(ClientWebSocket socket)
+ {
+ if (socket.State is not (WebSocketState.Open or WebSocketState.CloseReceived))
+ {
+ return;
+ }
+
+ using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(2));
+ try
+ {
+ await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Done", timeout.Token).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is WebSocketException or IOException or OperationCanceledException)
+ {
+ }
+ }
+
+ private static async Task PingLoopAsync(IPAddress address, int port, PhaseClock phase, List<(double Seconds, double Rtt)> pings, CancellationToken cancellationToken)
+ {
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ double at = phase.Seconds; // 0 until a stream is up; such samples are discarded.
+ if (await TcpPinger.PingAsync(address, port, TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false) is double rtt)
+ {
+ lock (pings)
+ {
+ pings.Add((at, rtt));
+ }
+ }
+
+ await Task.Delay(PingInterval, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ private static byte[] CreatePayload()
+ {
+ // ndt7 spec: binary messages SHOULD contain random data.
+ byte[] data = new byte[1 << 20];
+ RandomNumberGenerator.Fill(data);
+ return data;
+ }
+
+ /// Phase time measured from the moment the first stream connected.
+ private sealed class PhaseClock(Stopwatch clock)
+ {
+ private long _originTicks = -1;
+
+ public Stopwatch Clock => clock;
+
+ public bool Started => Interlocked.Read(ref _originTicks) >= 0;
+
+ public double Seconds
+ {
+ get
+ {
+ long origin = Interlocked.Read(ref _originTicks);
+ return origin < 0 ? 0 : TimeSpan.FromTicks(clock.Elapsed.Ticks - origin).TotalSeconds;
+ }
+ }
+
+ public void MarkStarted() => Interlocked.CompareExchange(ref _originTicks, clock.Elapsed.Ticks, -1);
+ }
+
+ private sealed class StreamCounters
+ {
+ public long ClientBytes;
+ public long ServerAppBytes;
+ private readonly List _rttMs = [];
+
+ public bool Connected { get; set; }
+
+ public int ServerMessages { get; private set; }
+
+ public long? MinRttMicroseconds { get; private set; }
+
+ public string? ClientAddress { get; private set; }
+
+ public string? Uuid { get; private set; }
+
+ public void OnMeasurement(MlabProtocolKind kind, TestDirection direction, ReadOnlySpan json)
+ {
+ if (!MeasurementParser.TryParse(kind, direction, json, out ServerMeasurement m))
+ {
+ return;
+ }
+
+ ServerMessages++;
+ if (m.AppBytes is long bytes && bytes > Interlocked.Read(ref ServerAppBytes))
+ {
+ Interlocked.Exchange(ref ServerAppBytes, bytes);
+ }
+
+ if (m.RttMicroseconds is long rtt and > 0)
+ {
+ lock (_rttMs)
+ {
+ _rttMs.Add(rtt / 1000d);
+ }
+ }
+
+ if (m.MinRttMicroseconds is long min and > 0 && (MinRttMicroseconds is null || min < MinRttMicroseconds))
+ {
+ MinRttMicroseconds = min;
+ }
+
+ ClientAddress ??= m.ClientAddress;
+ Uuid ??= m.Uuid;
+ }
+
+ public double[] RttSnapshot()
+ {
+ lock (_rttMs)
+ {
+ return [.. _rttMs];
+ }
+ }
+ }
+}
diff --git a/NetSpeed.Core/Mlab/TestUriBuilder.cs b/NetSpeed.Core/Mlab/TestUriBuilder.cs
new file mode 100644
index 0000000..98094d3
--- /dev/null
+++ b/NetSpeed.Core/Mlab/TestUriBuilder.cs
@@ -0,0 +1,44 @@
+using System.Text;
+
+namespace NetSpeed.Core.Mlab;
+
+public static class TestUriBuilder
+{
+ ///
+ /// Appends query parameters to a Locate URL. Existing keys (e.g. access_token) are kept and
+ /// never duplicated (ndt7 spec: clients MUST NOT send duplicate keys or keys without a value).
+ /// Parameters with an empty value are skipped.
+ ///
+ public static Uri AddQuery(Uri baseUri, IEnumerable> parameters)
+ {
+ ArgumentNullException.ThrowIfNull(baseUri);
+ ArgumentNullException.ThrowIfNull(parameters);
+
+ string query = baseUri.Query.TrimStart('?');
+ HashSet existing = new(StringComparer.Ordinal);
+ foreach (string part in query.Split('&', StringSplitOptions.RemoveEmptyEntries))
+ {
+ int eq = part.IndexOf('=', StringComparison.Ordinal);
+ existing.Add(Uri.UnescapeDataString(eq < 0 ? part : part[..eq]));
+ }
+
+ StringBuilder builder = new(query);
+ foreach ((string key, string value) in parameters)
+ {
+ if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(value) || !existing.Add(key))
+ {
+ continue;
+ }
+
+ if (builder.Length > 0)
+ {
+ builder.Append('&');
+ }
+
+ builder.Append(Uri.EscapeDataString(key)).Append('=').Append(Uri.EscapeDataString(value));
+ }
+
+ UriBuilder result = new(baseUri) { Query = builder.ToString() };
+ return result.Uri;
+ }
+}
diff --git a/NetSpeed.Core/NetSpeed.Core.csproj b/NetSpeed.Core/NetSpeed.Core.csproj
new file mode 100644
index 0000000..0d658c6
--- /dev/null
+++ b/NetSpeed.Core/NetSpeed.Core.csproj
@@ -0,0 +1,18 @@
+
+
+
+ net10.0
+ NetSpeed.Core
+ enable
+ enable
+ true
+ true
+
+
+
+
+
+
diff --git a/NetSpeed.Core/ResultFormatter.cs b/NetSpeed.Core/ResultFormatter.cs
new file mode 100644
index 0000000..f79d003
--- /dev/null
+++ b/NetSpeed.Core/ResultFormatter.cs
@@ -0,0 +1,56 @@
+using System.Globalization;
+using System.Text;
+
+namespace NetSpeed.Core;
+
+public static class ResultFormatter
+{
+ private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
+
+ public static string Mbps(double value) => value.ToString(value >= 100 ? "0" : "0.0", Invariant);
+
+ public static string Ms(double? value) => value is double v ? v.ToString("0.0", Invariant) + " ms" : "n/a";
+
+ public static string Bytes(long bytes)
+ {
+ const double kib = 1024d;
+ const double mib = kib * 1024d;
+ const double gib = mib * 1024d;
+ return bytes switch
+ {
+ >= (long)gib => (bytes / gib).ToString("0.00", Invariant) + " GiB",
+ >= (long)mib => (bytes / mib).ToString("0.0", Invariant) + " MiB",
+ >= (long)kib => (bytes / kib).ToString("0.0", Invariant) + " KiB",
+ _ => bytes.ToString(Invariant) + " B",
+ };
+ }
+
+ public static string ServerPlace(SpeedResult result)
+ {
+ ArgumentNullException.ThrowIfNull(result);
+ string place = string.Join(", ", new[] { result.ServerCity, result.ServerCountry }.Where(p => !string.IsNullOrWhiteSpace(p)));
+ return string.IsNullOrEmpty(place) ? result.ServerMachine : place;
+ }
+
+ /// Plain-text summary for the clipboard. The client IP address is deliberately omitted.
+ public static string ToClipboardText(SpeedResult result)
+ {
+ ArgumentNullException.ThrowIfNull(result);
+
+ StringBuilder sb = new();
+ sb.AppendLine(Invariant, $"NetSpeed result — {result.Timestamp.ToString("yyyy-MM-dd HH:mm:ss zzz", Invariant)}");
+ sb.AppendLine(Invariant, $"Download: {Mbps(result.DownloadMbps)} Mbps (full-phase average {Mbps(result.DownloadAverageMbps)} Mbps)");
+ sb.AppendLine(Invariant, $"Upload: {Mbps(result.UploadMbps)} Mbps (full-phase average {Mbps(result.UploadAverageMbps)} Mbps)");
+ sb.AppendLine(Invariant, $"Idle latency: {Ms(result.IdleLatencyMs)} • Jitter: {Ms(result.JitterMs)}");
+ sb.AppendLine(Invariant, $"Loaded latency: download {Ms(result.DownloadLoadedLatencyMs)} • upload {Ms(result.UploadLoadedLatencyMs)}");
+ if (result.BufferbloatMs is double bloat)
+ {
+ sb.AppendLine(Invariant, $"Bufferbloat: +{bloat.ToString("0", Invariant)} ms ({result.BufferbloatGrade})");
+ }
+
+ sb.AppendLine(Invariant, $"Server: {result.ServerMachine} ({ServerPlace(result)})");
+ sb.AppendLine(Invariant, $"Engine: {result.EngineName} {result.Protocol}, {result.Streams} stream(s)");
+ sb.Append(Invariant, $"Data: received {Bytes(result.BytesReceived)}, sent {Bytes(result.BytesSent)}");
+ return sb.ToString();
+ }
+}
diff --git a/NetSpeed.Core/SpeedModels.cs b/NetSpeed.Core/SpeedModels.cs
new file mode 100644
index 0000000..293d6b4
--- /dev/null
+++ b/NetSpeed.Core/SpeedModels.cs
@@ -0,0 +1,154 @@
+namespace NetSpeed.Core;
+
+/// A speed-test engine. Implementations must honour cancellation and report progress.
+public interface ISpeedEngine
+{
+ /// Human-readable engine name, e.g. "M-Lab".
+ string Name { get; }
+
+ Task RunAsync(IProgress? progress, CancellationToken cancellationToken);
+}
+
+public enum SpeedPhase
+{
+ Locating,
+ Latency,
+ Download,
+ Upload,
+}
+
+/// Live progress of a running test.
+/// Current phase.
+/// Overall progress, 0..1.
+/// Instantaneous throughput of the current phase, when measuring.
+/// Short status text (server, protocol, streams).
+public sealed record SpeedProgress(SpeedPhase Phase, double Fraction, double? CurrentMbps, string? Detail);
+
+/// Engine-neutral result of a complete speed test.
+public sealed class SpeedResult
+{
+ public required string EngineName { get; init; }
+
+ /// Protocol actually used, e.g. "MSAK throughput1" or "ndt7".
+ public required string Protocol { get; init; }
+
+ public required DateTimeOffset Timestamp { get; init; }
+
+ /// Download throughput after the TCP ramp-up (headline value).
+ public double DownloadMbps { get; init; }
+
+ /// Download throughput averaged over the whole phase, ramp-up included.
+ public double DownloadAverageMbps { get; init; }
+
+ public double UploadMbps { get; init; }
+
+ public double UploadAverageMbps { get; init; }
+
+ public double? IdleLatencyMs { get; init; }
+
+ public double? JitterMs { get; init; }
+
+ public double? DownloadLoadedLatencyMs { get; init; }
+
+ public double? UploadLoadedLatencyMs { get; init; }
+
+ /// How latency was measured, for transparency.
+ public string? LatencyMethod { get; init; }
+
+ public required string ServerMachine { get; init; }
+
+ public string? ServerCity { get; init; }
+
+ public string? ServerCountry { get; init; }
+
+ /// Public client address as seen by the server, without port.
+ public string? ClientAddress { get; init; }
+
+ /// ISP name. M-Lab does not return it, so this is null for the M-Lab engine.
+ public string? Isp { get; init; }
+
+ /// Approximate client location. Not returned by M-Lab.
+ public string? ClientLocation { get; init; }
+
+ public long BytesReceived { get; init; }
+
+ public long BytesSent { get; init; }
+
+ public int Streams { get; init; }
+
+ /// Extra latency added by load: worst loaded latency minus idle latency.
+ public double? BufferbloatMs
+ {
+ get
+ {
+ if (IdleLatencyMs is not double idle)
+ {
+ return null;
+ }
+
+ double? loaded = (DownloadLoadedLatencyMs, UploadLoadedLatencyMs) switch
+ {
+ (double d, double u) => Math.Max(d, u),
+ (double d, null) => d,
+ (null, double u) => u,
+ _ => null,
+ };
+
+ return loaded is double l ? Math.Max(0, l - idle) : null;
+ }
+ }
+
+ public string? BufferbloatGrade => BufferbloatMs switch
+ {
+ null => null,
+ < 30 => "Low",
+ < 100 => "Moderate",
+ _ => "High",
+ };
+}
+
+public enum SpeedTestErrorKind
+{
+ /// M-Lab Locate returned 204: no capacity right now.
+ NoCapacity,
+
+ /// Locate v2 failed or returned an unusable answer.
+ LocateFailed,
+
+ /// Every candidate server refused the connection.
+ AllServersRejected,
+
+ Timeout,
+
+ Network,
+
+ Protocol,
+
+ /// The local fair-use limit (M-Lab AUP: 40 tests/day) was reached.
+ RateLimited,
+}
+
+public sealed class SpeedTestException : Exception
+{
+ public SpeedTestException()
+ {
+ }
+
+ public SpeedTestException(string message)
+ : base(message)
+ {
+ }
+
+ public SpeedTestException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+
+ public SpeedTestException(SpeedTestErrorKind kind, string message, Exception? innerException = null)
+ : base(message, innerException)
+ {
+ Kind = kind;
+ }
+
+ public SpeedTestErrorKind Kind { get; } = SpeedTestErrorKind.Protocol;
+}
diff --git a/NetSpeed.sln b/NetSpeed.sln
index 830001e..b38524e 100644
--- a/NetSpeed.sln
+++ b/NetSpeed.sln
@@ -1,27 +1,81 @@
+
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetSpeed", "NetSpeed\NetSpeed.csproj", "{EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetSpeed.Core", "NetSpeed.Core\NetSpeed.Core.csproj", "{A9BAA006-809A-4FD1-B342-38904014F59E}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetSpeed.Core.Tests", "tests\NetSpeed.Core.Tests\NetSpeed.Core.Tests.csproj", "{C92E4B75-1259-413E-85A7-1F8911E4A525}"
+EndProject
Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|x64 = Debug|x64
- Debug|ARM64 = Debug|ARM64
- Release|x64 = Release|x64
- Release|ARM64 = Release|ARM64
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|x64.ActiveCfg = Debug|x64
- {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|x64.Build.0 = Debug|x64
- {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|ARM64.ActiveCfg = Debug|ARM64
- {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|ARM64.Build.0 = Debug|ARM64
- {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|x64.ActiveCfg = Release|x64
- {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|x64.Build.0 = Release|x64
- {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|ARM64.ActiveCfg = Release|ARM64
- {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|ARM64.Build.0 = Release|ARM64
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|x64 = Debug|x64
+ Debug|ARM64 = Debug|ARM64
+ Debug|Any CPU = Debug|Any CPU
+ Debug|x86 = Debug|x86
+ Release|x64 = Release|x64
+ Release|ARM64 = Release|ARM64
+ Release|Any CPU = Release|Any CPU
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|x64.ActiveCfg = Debug|x64
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|x64.Build.0 = Debug|x64
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|ARM64.ActiveCfg = Debug|ARM64
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|ARM64.Build.0 = Debug|ARM64
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Debug|x86.Build.0 = Debug|Any CPU
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|x64.ActiveCfg = Release|x64
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|x64.Build.0 = Release|x64
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|ARM64.ActiveCfg = Release|ARM64
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|ARM64.Build.0 = Release|ARM64
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|Any CPU.Build.0 = Release|Any CPU
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|x86.ActiveCfg = Release|Any CPU
+ {EB2F06E7-6E49-481C-AD71-9A4ECFC55DBE}.Release|x86.Build.0 = Release|Any CPU
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Debug|x64.ActiveCfg = Debug|x64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Debug|x64.Build.0 = Debug|x64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Debug|ARM64.ActiveCfg = Debug|ARM64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Debug|ARM64.Build.0 = Debug|ARM64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Debug|Any CPU.ActiveCfg = Debug|x64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Debug|Any CPU.Build.0 = Debug|x64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Debug|x86.ActiveCfg = Debug|x64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Debug|x86.Build.0 = Debug|x64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Release|x64.ActiveCfg = Release|x64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Release|x64.Build.0 = Release|x64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Release|ARM64.ActiveCfg = Release|ARM64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Release|ARM64.Build.0 = Release|ARM64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Release|Any CPU.ActiveCfg = Release|x64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Release|Any CPU.Build.0 = Release|x64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Release|x86.ActiveCfg = Release|x64
+ {A9BAA006-809A-4FD1-B342-38904014F59E}.Release|x86.Build.0 = Release|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Debug|x64.ActiveCfg = Debug|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Debug|x64.Build.0 = Debug|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Debug|ARM64.ActiveCfg = Debug|ARM64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Debug|ARM64.Build.0 = Debug|ARM64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Debug|Any CPU.ActiveCfg = Debug|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Debug|Any CPU.Build.0 = Debug|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Debug|x86.ActiveCfg = Debug|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Debug|x86.Build.0 = Debug|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Release|x64.ActiveCfg = Release|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Release|x64.Build.0 = Release|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Release|ARM64.ActiveCfg = Release|ARM64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Release|ARM64.Build.0 = Release|ARM64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Release|Any CPU.ActiveCfg = Release|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Release|Any CPU.Build.0 = Release|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Release|x86.ActiveCfg = Release|x64
+ {C92E4B75-1259-413E-85A7-1F8911E4A525}.Release|x86.Build.0 = Release|x64
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {C92E4B75-1259-413E-85A7-1F8911E4A525} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
+ EndGlobalSection
EndGlobal
diff --git a/NetSpeed/Commands/ActionCommand.cs b/NetSpeed/Commands/ActionCommand.cs
new file mode 100644
index 0000000..7d366db
--- /dev/null
+++ b/NetSpeed/Commands/ActionCommand.cs
@@ -0,0 +1,24 @@
+using Microsoft.CommandPalette.Extensions.Toolkit;
+
+namespace NetSpeed;
+
+/// Runs an action and keeps Command Palette open on the current page.
+internal sealed partial class ActionCommand : InvokableCommand
+{
+ private readonly Action _action;
+ private readonly string _name;
+
+ public ActionCommand(string name, Action action)
+ {
+ _name = name;
+ _action = action;
+ }
+
+ public override string Name => _name;
+
+ public override CommandResult Invoke()
+ {
+ _action();
+ return CommandResult.KeepOpen();
+ }
+}
diff --git a/NetSpeed/Commands/RunSpeedTestCommand.cs b/NetSpeed/Commands/RunSpeedTestCommand.cs
deleted file mode 100644
index cef84bc..0000000
--- a/NetSpeed/Commands/RunSpeedTestCommand.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using Microsoft.CommandPalette.Extensions.Toolkit;
-
-namespace NetSpeed;
-
-internal sealed partial class RunSpeedTestCommand : InvokableCommand
-{
- private readonly Action _run;
-
- public RunSpeedTestCommand(Action run)
- {
- _run = run;
- }
-
- public override string Name => "Run speed test";
-
- public override CommandResult Invoke()
- {
- _run();
- return CommandResult.KeepOpen();
- }
-}
diff --git a/NetSpeed/Models/LibreSpeedResult.cs b/NetSpeed/Models/LibreSpeedResult.cs
deleted file mode 100644
index 5656331..0000000
--- a/NetSpeed/Models/LibreSpeedResult.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-using System.Text.Json.Serialization;
-
-namespace NetSpeed;
-
-public sealed class LibreSpeedResult
-{
- [JsonPropertyName("timestamp")]
- public DateTimeOffset Timestamp { get; set; }
-
- [JsonPropertyName("server")]
- public LibreSpeedServer Server { get; set; } = new();
-
- [JsonPropertyName("client")]
- public LibreSpeedClient Client { get; set; } = new();
-
- [JsonPropertyName("bytes_sent")]
- public ulong BytesSent { get; set; }
-
- [JsonPropertyName("bytes_received")]
- public ulong BytesReceived { get; set; }
-
- [JsonPropertyName("ping")]
- public double Ping { get; set; }
-
- [JsonPropertyName("jitter")]
- public double Jitter { get; set; }
-
- [JsonPropertyName("upload")]
- public double Upload { get; set; }
-
- [JsonPropertyName("download")]
- public double Download { get; set; }
-
- [JsonPropertyName("share")]
- public string? Share { get; set; }
-}
-
-public sealed class LibreSpeedServer
-{
- [JsonPropertyName("name")]
- public string? Name { get; set; }
-
- [JsonPropertyName("url")]
- public string? Url { get; set; }
-}
-
-public sealed class LibreSpeedClient
-{
- [JsonPropertyName("ip")]
- public string? Ip { get; set; }
-
- [JsonPropertyName("hostname")]
- public string? Hostname { get; set; }
-
- [JsonPropertyName("city")]
- public string? City { get; set; }
-
- [JsonPropertyName("region")]
- public string? Region { get; set; }
-
- [JsonPropertyName("country")]
- public string? Country { get; set; }
-
- [JsonPropertyName("loc")]
- public string? Location { get; set; }
-
- [JsonPropertyName("org")]
- public string? Organization { get; set; }
-
- [JsonPropertyName("postal")]
- public string? Postal { get; set; }
-
- [JsonPropertyName("timezone")]
- public string? Timezone { get; set; }
-}
diff --git a/NetSpeed/Models/NetSpeedJsonContext.cs b/NetSpeed/Models/NetSpeedJsonContext.cs
deleted file mode 100644
index c523947..0000000
--- a/NetSpeed/Models/NetSpeedJsonContext.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-using System.Text.Json.Serialization;
-
-namespace NetSpeed;
-
-[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true)]
-[JsonSerializable(typeof(LibreSpeedResult))]
-internal partial class NetSpeedJsonContext : JsonSerializerContext
-{
-}
diff --git a/NetSpeed/NetSpeed.csproj b/NetSpeed/NetSpeed.csproj
index e1791bf..8372417 100644
--- a/NetSpeed/NetSpeed.csproj
+++ b/NetSpeed/NetSpeed.csproj
@@ -17,7 +17,7 @@
MicheleGentilini.NetSpeed.CmdPal
CN=GENTILINI MICHELE, O=GENTILINI MICHELE, L=Palazzuolo sul Senio, S=Firenze, C=IT
- 0.1.1.0
+ 0.2.0.0
@@ -28,14 +28,10 @@
-
- PreserveNewest
- PreserveNewest
-
-
- PreserveNewest
- PreserveNewest
-
+
+
+
+
diff --git a/NetSpeed/Package.appxmanifest b/NetSpeed/Package.appxmanifest
index 363a015..4aee496 100644
--- a/NetSpeed/Package.appxmanifest
+++ b/NetSpeed/Package.appxmanifest
@@ -7,11 +7,11 @@
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap uap3 rescap">
-
+
NetSpeed
- Michele Gentilini
+ g_
Assets\StoreLogo.png
@@ -49,7 +49,7 @@
Id="NetSpeed"
PublicFolder="Public"
DisplayName="NetSpeed"
- Description="Internet speed test powered by LibreSpeed">
+ Description="Internet speed test powered by Measurement Lab (M-Lab)">
diff --git a/NetSpeed/Pages/NetSpeedPage.cs b/NetSpeed/Pages/NetSpeedPage.cs
index c164587..5066782 100644
--- a/NetSpeed/Pages/NetSpeedPage.cs
+++ b/NetSpeed/Pages/NetSpeedPage.cs
@@ -1,17 +1,35 @@
+using System.Diagnostics;
using System.Globalization;
-using System.Threading;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
+using NetSpeed.Core;
+using NetSpeed.Core.Mlab;
namespace NetSpeed;
internal sealed partial class NetSpeedPage : ListPage
{
- private static readonly CultureInfo DisplayCulture = CultureInfo.InvariantCulture;
+ public const string Version = "0.2.0";
+ public const string DeveloperWebsite = "https://genty.me/";
+ public const string MlabWebsite = "https://www.measurementlab.net/";
+ public const string MlabPrivacyPolicy = "https://www.measurementlab.net/privacy/";
+ public const string MlabAup = "https://www.measurementlab.net/aup/";
+ public const string ProjectPrivacy = "https://github.com/mrgenty/NetSpeed-CmdPal/blob/main/PRIVACY.md";
- private readonly SpeedTestService _speedTest = new();
+ private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
+ private static readonly TimeSpan OverallTimeout = TimeSpan.FromSeconds(90);
+ private static readonly TimeSpan UiRefreshInterval = TimeSpan.FromMilliseconds(250);
+ private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(15) };
+
+ private readonly LocalStateStore _state = new(LocalStateStore.DefaultPath);
+#pragma warning disable CA1859 // The page depends on the engine abstraction on purpose.
+ private readonly ISpeedEngine _engine = new MlabEngine(Http, new MlabEngineOptions { ClientVersion = Version });
+#pragma warning restore CA1859
+ private readonly Lock _progressGate = new();
private IListItem[] _items;
private int _testInProgress;
+ private CancellationTokenSource? _cts;
+ private long _lastRefreshTicks;
public NetSpeedPage()
{
@@ -21,13 +39,39 @@ public NetSpeedPage()
_items = BuildIdleItems();
}
- public override IListItem[] GetItems() => _items;
+ public override IListItem[] GetItems() => Volatile.Read(ref _items);
+
+ private void SetItems(IListItem[] items)
+ {
+ Volatile.Write(ref _items, items);
+ RaiseItemsChanged();
+ }
private void RequestRun()
{
+ if (!_state.HasConsent)
+ {
+ SetItems(BuildConsentItems());
+ return;
+ }
+
+ _ = RunAsync();
+ }
+
+ private void AcceptAndRun()
+ {
+ _state.GrantConsent();
_ = RunAsync();
}
+ private void RevokeConsent()
+ {
+ _state.RevokeConsent();
+ SetItems(BuildIdleItems());
+ }
+
+ private void Cancel() => _cts?.Cancel();
+
private async Task RunAsync()
{
if (Interlocked.Exchange(ref _testInProgress, 1) == 1)
@@ -37,127 +81,257 @@ private async Task RunAsync()
try
{
- _items = BuildRunningItems();
- RaiseItemsChanged();
+ if (!_state.TryRegisterTest())
+ {
+ SetItems(BuildErrorItems(
+ "Daily test limit reached",
+ $"M-Lab's fair-use policy allows up to {LocalStateStore.MaxTestsPerDay} tests per day. Please try again later."));
+ return;
+ }
+
+ using CancellationTokenSource cts = new(OverallTimeout);
+ _cts = cts;
+ IsLoading = true;
+ SetItems(BuildRunningItems(new SpeedProgress(SpeedPhase.Locating, 0, null, "Contacting M-Lab…")));
- LibreSpeedResult result = await _speedTest.RunAsync().ConfigureAwait(false);
- _items = BuildResultItems(result);
+ InlineProgress progress = new(OnProgress);
+ try
+ {
+ SpeedResult result = await Task.Run(() => _engine.RunAsync(progress, cts.Token), cts.Token).ConfigureAwait(false);
+ SetItems(BuildResultItems(result));
+ }
+ catch (OperationCanceledException) when (cts.IsCancellationRequested)
+ {
+ bool timedOut = cts.Token.IsCancellationRequested && !_userCancelled;
+ SetItems(timedOut
+ ? BuildErrorItems("Speed test timed out", $"The test did not finish within {OverallTimeout.TotalSeconds:0} seconds and was stopped.")
+ : BuildIdleItems("Speed test cancelled."));
+ }
+ catch (SpeedTestException ex)
+ {
+ SetItems(BuildErrorItems(ErrorTitle(ex.Kind), FriendlyMessage(ex.Message)));
+ }
+ catch (Exception ex) when (ex is HttpRequestException or System.Net.Sockets.SocketException or IOException)
+ {
+ SetItems(BuildErrorItems("Network error", FriendlyMessage(ex.Message)));
+ }
+#pragma warning disable CA1031 // Last line of defence: never crash the extension host.
+ catch (Exception ex)
+#pragma warning restore CA1031
+ {
+ Debug.WriteLine(ex);
+ SetItems(BuildErrorItems("Speed test failed", FriendlyMessage(ex.Message)));
+ }
}
- catch (TimeoutException ex)
+ finally
{
- _items = BuildErrorItems("Speed test timed out", ex.Message);
+ _cts = null;
+ _userCancelled = false;
+ IsLoading = false;
+ Volatile.Write(ref _testInProgress, 0);
}
- catch (FileNotFoundException ex)
+ }
+
+ private bool _userCancelled;
+
+ private void UserCancel()
+ {
+ _userCancelled = true;
+ Cancel();
+ }
+
+ private void OnProgress(SpeedProgress p)
+ {
+ // Throttle UI refreshes; always show phase changes.
+ long now = Stopwatch.GetTimestamp();
+ lock (_progressGate)
{
- _items = BuildErrorItems("LibreSpeed component missing", ex.Message);
+ if (p.CurrentMbps is not null && Stopwatch.GetElapsedTime(_lastRefreshTicks, now) < UiRefreshInterval)
+ {
+ return;
+ }
+
+ _lastRefreshTicks = now;
}
- catch (Exception ex)
+
+ if (Volatile.Read(ref _testInProgress) == 1)
{
- _items = BuildErrorItems("Speed test failed", FriendlyMessage(ex.Message));
+ SetItems(BuildRunningItems(p));
}
- finally
+ }
+
+ // ---- Item builders ----------------------------------------------------
+
+ private IListItem[] BuildIdleItems(string? notice = null)
+ {
+ List items =
+ [
+ new ListItem(new ActionCommand("Run speed test", RequestRun))
+ {
+ Title = "▶ Run speed test",
+ Subtitle = notice ?? "Download, upload, latency, jitter and bufferbloat via Measurement Lab (M-Lab)",
+ },
+ new ListItem(new OpenUrlCommand(MlabWebsite))
+ {
+ Title = "Powered by Measurement Lab (M-Lab)",
+ Subtitle = "Open, non-commercial Internet measurement platform • results are published as open data",
+ },
+ ];
+
+ if (_state.HasConsent)
{
- Volatile.Write(ref _testInProgress, 0);
- RaiseItemsChanged();
+ items.Add(new ListItem(new ActionCommand("Withdraw consent", RevokeConsent))
+ {
+ Title = "Withdraw data-policy consent",
+ Subtitle = "NetSpeed will ask again before the next test",
+ });
}
+
+ items.Add(new ListItem(new OpenUrlCommand(DeveloperWebsite))
+ {
+ Title = "Developer: g_",
+ Subtitle = "genty.me",
+ });
+ return [.. items];
}
- private IListItem[] BuildIdleItems() =>
+ private IListItem[] BuildConsentItems() =>
[
- new ListItem(new RunSpeedTestCommand(RequestRun))
+ new ListItem(new NoOpCommand())
{
- Title = "▶ Run speed test",
- Subtitle = "Measures ping, jitter, download and upload using the fastest available LibreSpeed server",
+ Title = "Before your first test: your result becomes public data",
+ Subtitle = "Tests run on M-Lab servers. M-Lab publishes every result, including your public IP address, as open data.",
},
- new ListItem(new NoOpCommand())
+ new ListItem(new ActionCommand("Agree and run", AcceptAndRun))
{
- Title = "Privacy-first",
- Subtitle = "No NetSpeed telemetry and no result sharing. Only traffic required by the speed test is generated.",
+ Title = "✓ I agree — run the speed test",
+ Subtitle = "You accept M-Lab's privacy policy and acceptable use policy. Your choice is saved on this device only.",
},
- new ListItem(new OpenUrlCommand(SpeedTestService.LibreSpeedWebsite))
+ new ListItem(new OpenUrlCommand(MlabPrivacyPolicy))
{
- Title = "LibreSpeed",
- Subtitle = "Open librespeed.org",
+ Title = "Read M-Lab privacy policy",
+ Subtitle = MlabPrivacyPolicy,
},
- new ListItem(new OpenUrlCommand(SpeedTestService.DeveloperWebsite))
+ new ListItem(new OpenUrlCommand(MlabAup))
{
- Title = "Developer: Michele Gentilini",
- Subtitle = "genty.me",
+ Title = "Read M-Lab acceptable use policy",
+ Subtitle = MlabAup,
},
- ];
-
- private IListItem[] BuildRunningItems() =>
- [
- new ListItem(new NoOpCommand())
+ new ListItem(new OpenUrlCommand(ProjectPrivacy))
{
- Title = "⏱ Speed test in progress…",
- Subtitle = "Selecting the fastest server, then testing download and upload. This can take around 20–30 seconds.",
+ Title = "Read NetSpeed privacy notice",
+ Subtitle = "What NetSpeed itself stores (nothing leaves your PC except the test traffic)",
},
- new ListItem(new NoOpCommand())
+ new ListItem(new ActionCommand("Not now", () => SetItems(BuildIdleItems("No test was run."))))
{
- Title = "Please keep this page open",
- Subtitle = "NetSpeed is using LibreSpeed public test infrastructure.",
+ Title = "Not now",
+ Subtitle = "Go back without testing",
},
];
- private IListItem[] BuildResultItems(LibreSpeedResult r)
+ private IListItem[] BuildRunningItems(SpeedProgress p)
{
- string serverName = string.IsNullOrWhiteSpace(r.Server.Name) ? "LibreSpeed server" : r.Server.Name;
- string serverHost = GetHost(r.Server.Url);
- string organization = string.IsNullOrWhiteSpace(r.Client.Organization) ? "ISP unavailable" : r.Client.Organization;
- string location = BuildLocation(r.Client);
- string testedAt = r.Timestamp == default
- ? DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss", DisplayCulture)
- : r.Timestamp.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", DisplayCulture);
+ string percent = (Math.Clamp(p.Fraction, 0, 1) * 100).ToString("0", Invariant) + "%";
+ string title = p.Phase switch
+ {
+ SpeedPhase.Download => $"↓ {ResultFormatter.Mbps(p.CurrentMbps ?? 0)} Mbps",
+ SpeedPhase.Upload => $"↑ {ResultFormatter.Mbps(p.CurrentMbps ?? 0)} Mbps",
+ SpeedPhase.Latency => "⏱ Measuring latency…",
+ _ => "⏱ Preparing speed test…",
+ };
+ string phase = p.Phase switch
+ {
+ SpeedPhase.Download => "Download",
+ SpeedPhase.Upload => "Upload",
+ SpeedPhase.Latency => "Latency",
+ _ => "Locating server",
+ };
return
[
new ListItem(new NoOpCommand())
{
- Title = $"↓ {N(r.Download)} Mbps",
- Subtitle = "Download",
+ Title = title,
+ Subtitle = $"{phase} • {percent}" + (string.IsNullOrEmpty(p.Detail) ? string.Empty : $" • {p.Detail}"),
},
- new ListItem(new NoOpCommand())
+ new ListItem(new ActionCommand("Cancel", UserCancel))
{
- Title = $"↑ {N(r.Upload)} Mbps",
- Subtitle = "Upload",
- },
- new ListItem(new NoOpCommand())
- {
- Title = $"Latency {N(r.Ping)} ms",
- Subtitle = $"Jitter {N(r.Jitter)} ms",
+ Title = "✕ Cancel test",
+ Subtitle = "Stop the test now",
},
+ ];
+ }
+
+ private IListItem[] BuildResultItems(SpeedResult r)
+ {
+ string latencySubtitle = r.JitterMs is double jitter
+ ? $"Idle latency • jitter {ResultFormatter.Ms(jitter)} • {r.LatencyMethod}"
+ : $"Idle latency • {r.LatencyMethod}";
+
+ List items =
+ [
new ListItem(new NoOpCommand())
{
- Title = serverName,
- Subtitle = string.IsNullOrWhiteSpace(serverHost) ? "Selected LibreSpeed server" : $"Server: {serverHost}",
+ Title = $"↓ {ResultFormatter.Mbps(r.DownloadMbps)} Mbps",
+ Subtitle = $"Download (after ramp-up) • full-phase average {ResultFormatter.Mbps(r.DownloadAverageMbps)} Mbps",
},
new ListItem(new NoOpCommand())
{
- Title = organization,
- Subtitle = string.IsNullOrWhiteSpace(location) ? "Client network" : location,
+ Title = $"↑ {ResultFormatter.Mbps(r.UploadMbps)} Mbps",
+ Subtitle = $"Upload (after ramp-up) • full-phase average {ResultFormatter.Mbps(r.UploadAverageMbps)} Mbps",
},
new ListItem(new NoOpCommand())
{
- Title = $"Transferred {FormatBytes(r.BytesReceived + r.BytesSent)}",
- Subtitle = $"Received {FormatBytes(r.BytesReceived)} • Sent {FormatBytes(r.BytesSent)} • {testedAt}",
- },
- new ListItem(new RunSpeedTestCommand(RequestRun))
- {
- Title = "↻ Run again",
- Subtitle = "Start a new speed test",
- },
- new ListItem(new OpenUrlCommand(SpeedTestService.LibreSpeedCliWebsite))
- {
- Title = "About the test engine",
- Subtitle = "LibreSpeed CLI 1.0.13 • LGPL-3.0",
- },
- new ListItem(new OpenUrlCommand(SpeedTestService.DeveloperWebsite))
- {
- Title = "Developer: Michele Gentilini",
- Subtitle = "genty.me",
+ Title = $"Latency {ResultFormatter.Ms(r.IdleLatencyMs)}",
+ Subtitle = latencySubtitle,
},
];
+
+ if (r.DownloadLoadedLatencyMs is not null || r.UploadLoadedLatencyMs is not null)
+ {
+ string bloat = r.BufferbloatMs is double b
+ ? $"Bufferbloat +{b.ToString("0", Invariant)} ms ({r.BufferbloatGrade})"
+ : "Bufferbloat n/a";
+ items.Add(new ListItem(new NoOpCommand())
+ {
+ Title = bloat,
+ Subtitle = $"Latency under load: download {ResultFormatter.Ms(r.DownloadLoadedLatencyMs)} • upload {ResultFormatter.Ms(r.UploadLoadedLatencyMs)}",
+ });
+ }
+
+ items.Add(new ListItem(new CopyTextCommand(ResultFormatter.ToClipboardText(r)))
+ {
+ Title = "Copy result",
+ Subtitle = "Copy a plain-text summary (your IP address is not included)",
+ });
+ items.Add(new ListItem(new NoOpCommand())
+ {
+ Title = $"Server: {ResultFormatter.ServerPlace(r)}",
+ Subtitle = $"{r.ServerMachine} • {r.EngineName} {r.Protocol} • {r.Streams} stream{(r.Streams == 1 ? string.Empty : "s")}",
+ });
+ items.Add(new ListItem(new NoOpCommand())
+ {
+ Title = $"Transferred {ResultFormatter.Bytes(r.BytesReceived + r.BytesSent)}",
+ Subtitle = $"Received {ResultFormatter.Bytes(r.BytesReceived)} • sent {ResultFormatter.Bytes(r.BytesSent)} • "
+ + r.Timestamp.ToString("yyyy-MM-dd HH:mm:ss", Invariant)
+ + (r.ClientAddress is null ? string.Empty : $" • your IP {r.ClientAddress}"),
+ });
+ items.Add(new ListItem(new ActionCommand("Run again", RequestRun))
+ {
+ Title = "↻ Run again",
+ Subtitle = $"{_state.RemainingTests} of {LocalStateStore.MaxTestsPerDay} tests left in the last 24 hours (M-Lab fair use)",
+ });
+ items.Add(new ListItem(new OpenUrlCommand(MlabWebsite))
+ {
+ Title = "About Measurement Lab",
+ Subtitle = "This result is published by M-Lab as open data",
+ });
+ items.Add(new ListItem(new OpenUrlCommand(DeveloperWebsite))
+ {
+ Title = "Developer: g_",
+ Subtitle = "genty.me",
+ });
+ return [.. items];
}
private IListItem[] BuildErrorItems(string title, string detail) =>
@@ -167,45 +341,28 @@ private IListItem[] BuildErrorItems(string title, string detail) =>
Title = $"⚠ {title}",
Subtitle = detail,
},
- new ListItem(new RunSpeedTestCommand(RequestRun))
+ new ListItem(new ActionCommand("Try again", RequestRun))
{
Title = "↻ Try again",
Subtitle = "Start a new speed test",
},
- new ListItem(new OpenUrlCommand(SpeedTestService.LibreSpeedWebsite))
+ new ListItem(new OpenUrlCommand(MlabWebsite))
{
- Title = "Check LibreSpeed",
- Subtitle = "Open librespeed.org",
+ Title = "Measurement Lab status and information",
+ Subtitle = "measurementlab.net",
},
];
- private static string N(double value) => value.ToString("0.0", DisplayCulture);
-
- private static string GetHost(string? url)
+ private static string ErrorTitle(SpeedTestErrorKind kind) => kind switch
{
- return Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) ? uri.Host : string.Empty;
- }
-
- private static string BuildLocation(LibreSpeedClient client)
- {
- string[] parts = [client.City ?? string.Empty, client.Region ?? string.Empty, client.Country ?? string.Empty];
- return string.Join(", ", parts.Where(static part => !string.IsNullOrWhiteSpace(part)).Distinct(StringComparer.OrdinalIgnoreCase));
- }
-
- private static string FormatBytes(ulong bytes)
- {
- const double kib = 1024d;
- const double mib = kib * 1024d;
- const double gib = mib * 1024d;
-
- return bytes switch
- {
- >= (ulong)gib => $"{bytes / gib:0.00} GiB",
- >= (ulong)mib => $"{bytes / mib:0.0} MiB",
- >= (ulong)kib => $"{bytes / kib:0.0} KiB",
- _ => $"{bytes} B",
- };
- }
+ SpeedTestErrorKind.NoCapacity => "M-Lab is at capacity",
+ SpeedTestErrorKind.AllServersRejected => "Servers are busy",
+ SpeedTestErrorKind.LocateFailed => "No test server available",
+ SpeedTestErrorKind.Timeout => "Speed test timed out",
+ SpeedTestErrorKind.Network => "Network error",
+ SpeedTestErrorKind.RateLimited => "Daily test limit reached",
+ _ => "Speed test failed",
+ };
private static string FriendlyMessage(string message)
{
@@ -217,4 +374,13 @@ private static string FriendlyMessage(string message)
string singleLine = message.Replace('\r', ' ').Replace('\n', ' ').Trim();
return singleLine.Length <= 220 ? singleLine : singleLine[..217] + "…";
}
+
+ ///
+ /// Reports synchronously on the engine's thread. would post to the
+ /// thread pool (no synchronization context in the COM server) and could reorder updates.
+ ///
+ private sealed class InlineProgress(Action handler) : IProgress
+ {
+ public void Report(SpeedProgress value) => handler(value);
+ }
}
diff --git a/NetSpeed/Services/SpeedTestService.cs b/NetSpeed/Services/SpeedTestService.cs
deleted file mode 100644
index 8670918..0000000
--- a/NetSpeed/Services/SpeedTestService.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-using System.Diagnostics;
-using System.Text.Json;
-
-namespace NetSpeed;
-
-internal sealed class SpeedTestService
-{
- public const string LibreSpeedWebsite = "https://librespeed.org/";
- public const string LibreSpeedCliWebsite = "https://github.com/librespeed/speedtest-cli";
- public const string DeveloperWebsite = "https://genty.me/";
-
- private static readonly TimeSpan OverallTimeout = TimeSpan.FromSeconds(75);
-
- public async Task RunAsync()
- {
- string executable = Path.Combine(AppContext.BaseDirectory, "ThirdParty", "LibreSpeed", "librespeed-cli.exe");
- if (!File.Exists(executable))
- {
- throw new FileNotFoundException(
- "LibreSpeed CLI is missing from the package. Rebuild after running scripts/Prepare-LibreSpeed.ps1.",
- executable);
- }
-
- ProcessStartInfo startInfo = new()
- {
- FileName = executable,
- Arguments = "--json --no-icmp --duration 10 --concurrent 4 --timeout 15",
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- UseShellExecute = false,
- CreateNoWindow = true,
- WorkingDirectory = Path.GetDirectoryName(executable)!,
- };
-
- using Process process = new() { StartInfo = startInfo };
- if (!process.Start())
- {
- throw new InvalidOperationException("Unable to start LibreSpeed CLI.");
- }
-
- Task stdoutTask = process.StandardOutput.ReadToEndAsync();
- Task stderrTask = process.StandardError.ReadToEndAsync();
- using CancellationTokenSource timeout = new(OverallTimeout);
-
- try
- {
- await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false);
- }
- catch (OperationCanceledException)
- {
- TryKill(process);
- throw new TimeoutException("The speed test exceeded 75 seconds and was stopped.");
- }
-
- string stdout = (await stdoutTask.ConfigureAwait(false)).Trim();
- string stderr = (await stderrTask.ConfigureAwait(false)).Trim();
-
- if (process.ExitCode != 0)
- {
- string detail = string.IsNullOrWhiteSpace(stderr) ? "LibreSpeed CLI returned a non-zero exit code." : stderr;
- throw new InvalidOperationException(detail);
- }
-
- if (string.IsNullOrWhiteSpace(stdout))
- {
- throw new InvalidOperationException("LibreSpeed CLI returned an empty result.");
- }
-
- return ParseResult(stdout);
- }
-
- private static LibreSpeedResult ParseResult(string json)
- {
- try
- {
- using JsonDocument document = JsonDocument.Parse(json);
- JsonElement root = document.RootElement;
-
- // LibreSpeed CLI 1.0.13 emits a JSON array even when only one
- // server is tested. Older/alternate builds may emit one object,
- // so accept both shapes.
- JsonElement resultElement = root.ValueKind switch
- {
- JsonValueKind.Array when root.GetArrayLength() > 0 => root[0],
- JsonValueKind.Object => root,
- JsonValueKind.Array => throw new InvalidOperationException("LibreSpeed CLI returned an empty result array."),
- _ => throw new InvalidOperationException("LibreSpeed CLI returned an unsupported JSON structure."),
- };
-
- LibreSpeedResult? result = JsonSerializer.Deserialize(
- resultElement,
- NetSpeedJsonContext.Default.LibreSpeedResult);
-
- return result ?? throw new InvalidOperationException("LibreSpeed CLI returned no usable result.");
- }
- catch (JsonException ex)
- {
- throw new InvalidOperationException("LibreSpeed CLI returned invalid JSON.", ex);
- }
- }
-
- private static void TryKill(Process process)
- {
- try
- {
- if (!process.HasExited)
- {
- process.Kill(entireProcessTree: true);
- }
- }
- catch
- {
- // Best effort only: the process may have already exited.
- }
- }
-}
diff --git a/NetSpeed/ThirdParty/LibreSpeed/LICENSE-LGPL-3.0.txt b/NetSpeed/ThirdParty/LibreSpeed/LICENSE-LGPL-3.0.txt
deleted file mode 100644
index 0a04128..0000000
--- a/NetSpeed/ThirdParty/LibreSpeed/LICENSE-LGPL-3.0.txt
+++ /dev/null
@@ -1,165 +0,0 @@
- GNU LESSER GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-
- This version of the GNU Lesser General Public License incorporates
-the terms and conditions of version 3 of the GNU General Public
-License, supplemented by the additional permissions listed below.
-
- 0. Additional Definitions.
-
- As used herein, "this License" refers to version 3 of the GNU Lesser
-General Public License, and the "GNU GPL" refers to version 3 of the GNU
-General Public License.
-
- "The Library" refers to a covered work governed by this License,
-other than an Application or a Combined Work as defined below.
-
- An "Application" is any work that makes use of an interface provided
-by the Library, but which is not otherwise based on the Library.
-Defining a subclass of a class defined by the Library is deemed a mode
-of using an interface provided by the Library.
-
- A "Combined Work" is a work produced by combining or linking an
-Application with the Library. The particular version of the Library
-with which the Combined Work was made is also called the "Linked
-Version".
-
- The "Minimal Corresponding Source" for a Combined Work means the
-Corresponding Source for the Combined Work, excluding any source code
-for portions of the Combined Work that, considered in isolation, are
-based on the Application, and not on the Linked Version.
-
- The "Corresponding Application Code" for a Combined Work means the
-object code and/or source code for the Application, including any data
-and utility programs needed for reproducing the Combined Work from the
-Application, but excluding the System Libraries of the Combined Work.
-
- 1. Exception to Section 3 of the GNU GPL.
-
- You may convey a covered work under sections 3 and 4 of this License
-without being bound by section 3 of the GNU GPL.
-
- 2. Conveying Modified Versions.
-
- If you modify a copy of the Library, and, in your modifications, a
-facility refers to a function or data to be supplied by an Application
-that uses the facility (other than as an argument passed when the
-facility is invoked), then you may convey a copy of the modified
-version:
-
- a) under this License, provided that you make a good faith effort to
- ensure that, in the event an Application does not supply the
- function or data, the facility still operates, and performs
- whatever part of its purpose remains meaningful, or
-
- b) under the GNU GPL, with none of the additional permissions of
- this License applicable to that copy.
-
- 3. Object Code Incorporating Material from Library Header Files.
-
- The object code form of an Application may incorporate material from
-a header file that is part of the Library. You may convey such object
-code under terms of your choice, provided that, if the incorporated
-material is not limited to numerical parameters, data structure
-layouts and accessors, or small macros, inline functions and templates
-(ten or fewer lines in length), you do both of the following:
-
- a) Give prominent notice with each copy of the object code that the
- Library is used in it and that the Library and its use are
- covered by this License.
-
- b) Accompany the object code with a copy of the GNU GPL and this license
- document.
-
- 4. Combined Works.
-
- You may convey a Combined Work under terms of your choice that,
-taken together, effectively do not restrict modification of the
-portions of the Library contained in the Combined Work and reverse
-engineering for debugging such modifications, if you also do each of
-the following:
-
- a) Give prominent notice with each copy of the Combined Work that
- the Library is used in it and that the Library and its use are
- covered by this License.
-
- b) Accompany the Combined Work with a copy of the GNU GPL and this license
- document.
-
- c) For a Combined Work that displays copyright notices during
- execution, include the copyright notice for the Library among
- these notices, as well as a reference directing the user to the
- copies of the GNU GPL and this license document.
-
- d) Do one of the following:
-
- 0) Convey the Minimal Corresponding Source under the terms of this
- License, and the Corresponding Application Code in a form
- suitable for, and under terms that permit, the user to
- recombine or relink the Application with a modified version of
- the Linked Version to produce a modified Combined Work, in the
- manner specified by section 6 of the GNU GPL for conveying
- Corresponding Source.
-
- 1) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (a) uses at run time
- a copy of the Library already present on the user's computer
- system, and (b) will operate properly with a modified version
- of the Library that is interface-compatible with the Linked
- Version.
-
- e) Provide Installation Information, but only if you would otherwise
- be required to provide such information under section 6 of the
- GNU GPL, and only to the extent that such information is
- necessary to install and execute a modified version of the
- Combined Work produced by recombining or relinking the
- Application with a modified version of the Linked Version. (If
- you use option 4d0, the Installation Information must accompany
- the Minimal Corresponding Source and Corresponding Application
- Code. If you use option 4d1, you must provide the Installation
- Information in the manner specified by section 6 of the GNU GPL
- for conveying Corresponding Source.)
-
- 5. Combined Libraries.
-
- You may place library facilities that are a work based on the
-Library side by side in a single library together with other library
-facilities that are not Applications and are not covered by this
-License, and convey such a combined library under terms of your
-choice, if you do both of the following:
-
- a) Accompany the combined library with a copy of the same work based
- on the Library, uncombined with any other library facilities,
- conveyed under the terms of this License.
-
- b) Give prominent notice with the combined library that part of it
- is a work based on the Library, and explaining where to find the
- accompanying uncombined form of the same work.
-
- 6. Revised Versions of the GNU Lesser General Public License.
-
- The Free Software Foundation may publish revised and/or new versions
-of the GNU Lesser General Public License from time to time. Such new
-versions will be similar in spirit to the present version, but may
-differ in detail to address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Library as you received it specifies that a certain numbered version
-of the GNU Lesser General Public License "or any later version"
-applies to it, you have the option of following the terms and
-conditions either of that published version or of any later version
-published by the Free Software Foundation. If the Library as you
-received it does not specify a version number of the GNU Lesser
-General Public License, you may choose any version of the GNU Lesser
-General Public License ever published by the Free Software Foundation.
-
- If the Library as you received it specifies that a proxy can decide
-whether future versions of the GNU Lesser General Public License shall
-apply, that proxy's public statement of acceptance of any version is
-permanent authorization for you to choose that version for the
-Library.
diff --git a/PRIVACY.md b/PRIVACY.md
new file mode 100644
index 0000000..49c7cea
--- /dev/null
+++ b/PRIVACY.md
@@ -0,0 +1,57 @@
+# NetSpeed privacy notice
+
+_Last updated: 2026-11-27 — applies to NetSpeed 0.2.0 and later._
+
+NetSpeed is a free, open-source (MIT) extension for PowerToys Command Palette, developed by g_ ([genty.me](https://genty.me/)). It runs Internet speed tests on the **Measurement Lab (M-Lab)** platform. This notice explains what data is involved and who handles it.
+
+## Summary
+
+- NetSpeed has **no telemetry, analytics, accounts or servers of its own**.
+- A test runs **only when you start it**, and only after you have accepted the data notice shown before your first test.
+- The test itself is performed with M-Lab servers. **M-Lab publishes every test result, including your public IP address, as open data.**
+
+## What happens during a test
+
+When you start a test, NetSpeed:
+
+1. Asks the M-Lab Locate service (`locate.measurementlab.net`) for nearby test servers. Locate uses your IP address to estimate your approximate location and pick a nearby server.
+2. Opens a few TCP connections to the candidate servers to measure round-trip time (no data is sent on these connections) and picks the fastest-responding one.
+3. Runs a download and an upload test with the selected M-Lab server, using the M-Lab **MSAK throughput1** protocol (or **ndt7** as a fallback). Only random, synthetic data is transferred.
+
+The test servers record the measurement, including:
+
+- your **public IP address** and port as seen by the server;
+- throughput, timing and TCP statistics of the test connections;
+- the client identification NetSpeed sends: `client_name=netspeed-cmdpal`, the NetSpeed version, the operating system (`windows`) and the CPU architecture, plus a User-Agent naming NetSpeed.
+
+NetSpeed does **not** send hardware identifiers, account data, browsing data or any other personal information.
+
+## Who handles the data
+
+Test data is collected, stored and published by **M-Lab**, which acts as the data controller for test data under the GDPR and releases it into the public domain for research. Please read:
+
+- [M-Lab Privacy Policy](https://www.measurementlab.net/privacy/) — including how EU data subjects can exercise their rights;
+- [M-Lab Acceptable Use Policy](https://www.measurementlab.net/aup/).
+
+Because results are public and are linked to an IP address, do not run tests if you do not want that association to be published.
+
+## What NetSpeed stores on your device
+
+NetSpeed keeps one small file, `state.json`, in its local application data folder (inside the package's private storage when installed as MSIX). It contains:
+
+- whether and when you accepted the data notice (and which version of it);
+- the start times of your tests in the last 24 hours, used to respect M-Lab's limit of 40 tests per day for interactive users.
+
+This file never leaves your device. Uninstalling NetSpeed removes it.
+
+The **Copy result** command copies a text summary to your clipboard; it deliberately does not include your IP address.
+
+## Your choices
+
+- You can decline the notice: no test is run and nothing is sent.
+- You can withdraw consent at any time with **Withdraw data-policy consent** on the NetSpeed page; NetSpeed will ask again before the next test.
+- Data already published by M-Lab can only be handled by M-Lab under its privacy policy.
+
+## Contact
+
+For questions about NetSpeed itself, open an issue on the project's GitHub repository or use the contact details at [genty.me](https://genty.me/). For questions about test data, contact M-Lab as described in its privacy policy.
diff --git a/PROJECT_INFO.txt b/PROJECT_INFO.txt
deleted file mode 100644
index acfe5b8..0000000
--- a/PROJECT_INFO.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-Project: NetSpeed for PowerToys Command Palette
-Version: 0.1.1
-Developer: Michele Gentilini
-Developer website: https://genty.me
-Speed-test engine: LibreSpeed CLI 1.0.13
-NetSpeed license: MIT
-LibreSpeed CLI license: LGPL-3.0
-Command Palette package identity: MicheleGentilini.NetSpeed.CmdPal
-COM CLSID: C71F961F-3B9A-4380-B42C-7E5712AEE055
diff --git a/README.md b/README.md
index d4374b6..6f5d131 100644
--- a/README.md
+++ b/README.md
@@ -1,80 +1,65 @@
# NetSpeed for PowerToys Command Palette
-A compact Internet speed test extension for **Microsoft PowerToys Command Palette**.
-
-NetSpeed runs a speed test on demand and shows the result directly inside Command Palette: download, upload, latency, jitter, selected server, ISP and transferred data.
-
+Internet speed test inside **PowerToys Command Palette**: download, upload, latency, jitter and bufferbloat, measured on the open **Measurement Lab (M-Lab)** platform.
## Features
-- One-command Internet speed test inside Command Palette
-- Download and upload speed in Mbps
-- Ping and jitter
-- Automatic fastest-server selection
-- Selected LibreSpeed server information
-- ISP and approximate client location returned by the test backend
-- Total received/sent data
-- No NetSpeed telemetry
-- No automatic test on launch: bandwidth is used only after the user explicitly starts a test
-- x64 and ARM64 build configuration
-- Release MSIX packages digitally signed with Microsoft Artifact Signing (Public Trust)
-
-## Speed-test engine
+- Live Mbps while testing, with Cancel
+- Download and upload: steady-state value (after TCP ramp-up) and full-phase average
+- Idle latency, jitter, latency under load and bufferbloat grade
+- Multi-stream test (MSAK, 4 TCP streams) for fast connections, with automatic ndt7 fallback
+- Nearest-server selection (M-Lab Locate + round-trip-time ranking)
+- **Copy result** as plain text (your IP address is left out)
+- No telemetry, no bundled executables
+- x64 and ARM64; release packages signed with Microsoft Artifact Signing
-NetSpeed uses **LibreSpeed CLI 1.0.13** as a separate executable component. LibreSpeed CLI is licensed under LGPL-3.0.
+## How it measures
-The project does not require LibreSpeed CLI to be installed globally. Before compilation, `scripts/Prepare-LibreSpeed.ps1` downloads the official upstream Windows binary for the requested architecture and verifies its SHA-256 against the checksum file published with the upstream release.
+`NetSpeed.Core` is a self-contained C# client for M-Lab, built on `HttpClient` and `ClientWebSocket`. It is AOT- and trim-compatible.
-The test uses LibreSpeed's public server list and automatic server selection. NetSpeed does not request result sharing and does not operate a telemetry backend of its own.
+1. **Server**: [Locate API v2](https://github.com/m-lab/locate/blob/main/USAGE.md) returns up to four nearby servers. NetSpeed picks the one with the fastest TCP handshake.
+2. **Idle latency and jitter**: 10 TCP handshakes before any load.
+3. **Download and upload**: 10 s each with [MSAK throughput1](https://github.com/m-lab/msak) over 4 streams. If MSAK is unavailable, NetSpeed falls back to [ndt7](https://github.com/m-lab/ndt-server/blob/main/spec/ndt7-protocol.md), which uses a single stream.
+ - Upload speed comes from the server's own counters.
+ - The headline value ignores the first 2 s of ramp-up.
+4. **Latency under load**: TCP handshakes every 250 ms while data flows. Bufferbloat is the worst loaded latency minus the idle latency.
-See `THIRD_PARTY_NOTICES.md` for licensing details.
+### Limits
-## Requirements
+- M-Lab servers are usually off your ISP's network, so services with in-ISP servers can report more, especially above 1 Gbps.
+- With the ndt7 fallback, a single stream may not saturate very fast links.
+- ISP name and location are not shown: M-Lab does not provide them, and NetSpeed calls no geolocation service.
-- Windows 11
-- PowerToys with Command Palette
-- .NET 10 SDK / Visual Studio with the Windows development workload for local builds
-- Internet access during dependency preparation and speed testing
+## Data and consent
-## Installation
+**M-Lab publishes every test result, including your public IP address, as open data.** NetSpeed tells you this before the first test and runs only after you agree. Your choice is stored locally and can be withdrawn.
-Download the MSIX package for your architecture from the project's GitHub release/artifacts:
+NetSpeed follows the [M-Lab Acceptable Use Policy](https://www.measurementlab.net/aup/):
-- `NetSpeed--x64.msix` for x64 Windows
-- `NetSpeed--ARM64.msix` for ARM64 Windows
+- the client identifies itself as `netspeed-cmdpal`;
+- tests run on demand only;
+- at most 40 tests run in 24 hours.
-Release packages are digitally signed using **Microsoft Artifact Signing (Public Trust)**. You do **not** need to install or import a separate signing certificate into `TrustedPeople`.
+See [PRIVACY.md](PRIVACY.md).
-Open the downloaded `.msix` file and install it with Windows App Installer. Then open PowerToys Command Palette; NetSpeed will be available as a Command Palette extension.
+## Installation
-> Debug/CI artifacts may use a temporary development certificate and are intended for testing only. For normal installation, use a signed release package.
+Download `NetSpeed--x64.msix` or `NetSpeed--ARM64.msix` from [Releases](https://github.com/mrgenty/NetSpeed-CmdPal/releases) and open it with App Installer. Release packages are publicly trusted: no certificate import is needed. Then open Command Palette and search for **NetSpeed**.
-## Local development
+## Development
-Open PowerShell from the repository root and prepare the LibreSpeed engine for your architecture:
+Requires the .NET 10 SDK, or Visual Studio with the Windows development workload. Open `NetSpeed.sln`, or run:
```powershell
-.\scripts\Prepare-LibreSpeed.ps1 -Architecture x64
+dotnet publish NetSpeed\NetSpeed.csproj -c Release -p:Platform=x64 -r win-x64 -p:GenerateAppxPackageOnBuild=true -p:AppxPackageSigningEnabled=false
```
-Then open `NetSpeed.sln` in Visual Studio and build/deploy the project.
-
-For ARM64:
-
```powershell
-.\scripts\Prepare-LibreSpeed.ps1 -Architecture ARM64
+dotnet test tests\NetSpeed.Core.Tests
```
-## Privacy
-
-NetSpeed has no proprietary analytics or telemetry service. A speed test necessarily transfers a significant amount of test data to/from the selected LibreSpeed server. The backend may also return public-IP/ISP information as part of the test result.
+The tests run on any OS and never contact M-Lab: a local fake WebSocket server exercises the real download and upload code. Clone to a short path (e.g. `C:\src`), because very deep folders can exceed the Windows path limit during CsWinRT code generation.
## License
-NetSpeed source code: **MIT License**, copyright © 2026 Michele Gentilini.
-
-LibreSpeed CLI: **LGPL-3.0**, distributed as a separate executable in built packages. See `THIRD_PARTY_NOTICES.md` and `NetSpeed/ThirdParty/LibreSpeed/LICENSE-LGPL-3.0.txt`.
-
-## Changelog
-
-See `CHANGELOG.md`. Version 0.1.1 fixes LibreSpeed CLI 1.0.13 JSON-array parsing.
+MIT © 2026 g_. Not affiliated with or endorsed by Measurement Lab, Microsoft or Ookla.
diff --git a/SECURITY.md b/SECURITY.md
deleted file mode 100644
index 94bcfd8..0000000
--- a/SECURITY.md
+++ /dev/null
@@ -1,98 +0,0 @@
-# Security Policy
-
-## Supported Versions
-
-NetSpeed is currently in early development. Security fixes are provided for the latest published release only.
-
-| Version | Supported |
-| ------- | --------- |
-| Latest release | :white_check_mark: |
-| Older releases | :x: |
-
-Users are encouraged to upgrade to the latest available version before reporting an issue.
-
-## Reporting a Vulnerability
-
-Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.
-
-If private vulnerability reporting is available for this repository, use the **Security** tab on GitHub and select **Report a vulnerability**.
-
-If private reporting is not available, open a public issue containing **no sensitive technical details** and request a private contact channel.
-
-When reporting a vulnerability, please include:
-
-- A clear description of the issue
-- The affected NetSpeed version
-- The affected Windows architecture (`x64` or `ARM64`)
-- Steps required to reproduce the issue
-- The expected and actual behavior
-- The potential security impact
-- Any relevant logs or screenshots, with sensitive information removed
-- A proposed fix or mitigation, if available
-
-Please avoid including credentials, private keys, certificates containing private keys, access tokens, personal data, or other secrets in reports.
-
-## Response Process
-
-Security reports will be reviewed as soon as reasonably possible.
-
-After receiving a report, the maintainer will:
-
-1. Confirm receipt of the report.
-2. Attempt to reproduce and validate the issue.
-3. Determine whether the issue affects NetSpeed itself or an upstream dependency.
-4. Prepare a fix or mitigation when appropriate.
-5. Coordinate disclosure after an updated version is available.
-
-Valid reports may be acknowledged in the release notes or security advisory, unless the reporter prefers to remain anonymous.
-
-There is currently no bug bounty or monetary reward program.
-
-## Scope
-
-Security issues affecting the following areas are considered in scope:
-
-- NetSpeed's PowerToys Command Palette extension
-- MSIX packaging and installation behavior
-- NetSpeed's interaction with LibreSpeed CLI
-- Input or output parsing that could result in unintended code execution or unsafe behavior
-- Unsafe handling of files, paths, processes, or network responses
-- Build and release pipeline issues that could compromise distributed NetSpeed packages
-- Signing or package-integrity issues affecting official NetSpeed releases
-- Leakage of information that NetSpeed is expected to keep private
-
-## Out of Scope
-
-The following are generally outside the scope of this project:
-
-- Vulnerabilities in Microsoft PowerToys itself
-- Vulnerabilities in Windows or the .NET runtime
-- Vulnerabilities entirely within LibreSpeed CLI that are not caused or amplified by NetSpeed's integration
-- Vulnerabilities in third-party LibreSpeed public servers
-- General availability or performance problems with public speed-test servers
-- ISP behavior, network filtering, or inaccurate speed-test results
-- Social engineering attacks
-- Denial-of-service reports that only involve intentionally running repeated bandwidth-intensive speed tests
-- Reports requiring a compromised operating system or administrator account before the attack can occur
-
-Upstream vulnerabilities should be reported directly to the affected upstream project whenever possible.
-
-## Security Considerations
-
-NetSpeed performs an Internet speed test only when explicitly requested by the user.
-
-Running a speed test transfers a significant amount of network traffic to and from a selected LibreSpeed server. The selected backend may receive information normally exposed during an Internet connection, such as the user's public IP address, and may return ISP or approximate location information.
-
-NetSpeed does not operate its own telemetry or analytics backend.
-
-Official MSIX packages are signed during the GitHub Actions release process. Users should obtain release packages only from the official NetSpeed repository and should verify that the package is signed with the expected NetSpeed signing certificate.
-
-The project currently uses a self-signed code-signing certificate. The requirement to explicitly trust that certificate before installing an official development release is expected behavior and is not, by itself, considered a security vulnerability.
-
-## Responsible Disclosure
-
-Please allow reasonable time for investigation and remediation before publicly disclosing a vulnerability.
-
-Do not access, modify, or destroy data belonging to other users, and do not perform testing that could disrupt third-party services.
-
-Good-faith security research that follows this policy is welcome.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
deleted file mode 100644
index 7474234..0000000
--- a/THIRD_PARTY_NOTICES.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# Third-party notices
-
-NetSpeed uses **LibreSpeed CLI** as a separate executable speed-test engine.
-
-- Project: LibreSpeed CLI
-- Upstream: https://github.com/librespeed/speedtest-cli
-- Version pinned by this project: 1.0.13
-- License: GNU Lesser General Public License v3.0 (LGPL-3.0)
-- Original authors retain all rights to LibreSpeed CLI.
-
-Release builds download the official upstream archive for the target Windows architecture and verify it against the SHA-256 value published in the upstream `checksums.txt` file before packaging it.
-
-The complete LGPL-3.0 license text is included at `NetSpeed/ThirdParty/LibreSpeed/LICENSE-LGPL-3.0.txt` and is also copied beside release artifacts.
-
-NetSpeed itself is licensed under the MIT License. NetSpeed is not affiliated with or endorsed by the LibreSpeed project, Microsoft, or Ookla.
diff --git a/scripts/Install-Package.ps1 b/scripts/Install-Package.ps1
deleted file mode 100644
index 5430de3..0000000
--- a/scripts/Install-Package.ps1
+++ /dev/null
@@ -1,31 +0,0 @@
-param(
- [string]$PackagePath,
- [string]$CertificatePath
-)
-
-$ErrorActionPreference = "Stop"
-
-if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
- throw "Run this script from PowerShell as Administrator."
-}
-
-if (-not $PackagePath) {
- $PackagePath = (Get-ChildItem -Path $PSScriptRoot -Filter "*.msix" | Select-Object -First 1).FullName
-}
-if (-not $CertificatePath) {
- $CertificatePath = (Get-ChildItem -Path $PSScriptRoot -Filter "*.cer" | Select-Object -First 1).FullName
-}
-
-if (-not $PackagePath -or -not (Test-Path $PackagePath)) {
- throw "MSIX package not found."
-}
-if (-not $CertificatePath -or -not (Test-Path $CertificatePath)) {
- throw "Signing certificate not found."
-}
-
-Write-Host "Importing development certificate into LocalMachine\TrustedPeople..."
-Import-Certificate -FilePath $CertificatePath -CertStoreLocation "Cert:\LocalMachine\TrustedPeople" | Out-Null
-
-Write-Host "Installing $PackagePath ..."
-Add-AppxPackage -Path $PackagePath
-Write-Host "NetSpeed installed. Open PowerToys Command Palette and search for 'NetSpeed'."
diff --git a/scripts/Prepare-LibreSpeed.ps1 b/scripts/Prepare-LibreSpeed.ps1
deleted file mode 100644
index cb41c0d..0000000
--- a/scripts/Prepare-LibreSpeed.ps1
+++ /dev/null
@@ -1,57 +0,0 @@
-param(
- [ValidateSet("x64", "ARM64")]
- [string]$Architecture = "x64",
- [string]$Version = "1.0.13"
-)
-
-$ErrorActionPreference = "Stop"
-
-$goArch = if ($Architecture -eq "ARM64") { "arm64" } else { "amd64" }
-$archiveName = "librespeed-cli_${Version}_windows_${goArch}.zip"
-$baseUrl = "https://github.com/librespeed/speedtest-cli/releases/download/v$Version"
-$projectRoot = Split-Path -Parent $PSScriptRoot
-$destination = Join-Path $projectRoot "NetSpeed\ThirdParty\LibreSpeed"
-$temp = Join-Path ([System.IO.Path]::GetTempPath()) ("netspeed-librespeed-" + [Guid]::NewGuid().ToString("N"))
-
-New-Item -ItemType Directory -Force -Path $destination | Out-Null
-New-Item -ItemType Directory -Force -Path $temp | Out-Null
-
-try {
- $archivePath = Join-Path $temp $archiveName
- $checksumsPath = Join-Path $temp "checksums.txt"
-
- Write-Host "Downloading LibreSpeed CLI v$Version for $Architecture..."
- Invoke-WebRequest -Uri "$baseUrl/$archiveName" -OutFile $archivePath
- Invoke-WebRequest -Uri "$baseUrl/checksums.txt" -OutFile $checksumsPath
-
- $checksumLine = Get-Content $checksumsPath | Where-Object { $_ -match [regex]::Escape($archiveName) } | Select-Object -First 1
- if (-not $checksumLine) {
- throw "Checksum for $archiveName was not found in the upstream checksums file."
- }
-
- $expected = ($checksumLine -split '\s+')[0].Trim().ToLowerInvariant()
- $actual = (Get-FileHash -Path $archivePath -Algorithm SHA256).Hash.ToLowerInvariant()
- if ($actual -ne $expected) {
- throw "SHA256 mismatch for $archiveName. Expected $expected, got $actual."
- }
-
- $expanded = Join-Path $temp "expanded"
- Expand-Archive -Path $archivePath -DestinationPath $expanded -Force
-
- $exe = Get-ChildItem -Path $expanded -Recurse -Filter "librespeed-cli.exe" | Select-Object -First 1
- if (-not $exe) {
- throw "librespeed-cli.exe was not found in the upstream archive."
- }
-
- Copy-Item $exe.FullName (Join-Path $destination "librespeed-cli.exe") -Force
-
- $license = Get-ChildItem -Path $expanded -Recurse -Filter "LICENSE" | Select-Object -First 1
- if ($license) {
- Copy-Item $license.FullName (Join-Path $destination "LICENSE-LGPL-3.0.txt") -Force
- }
-
- Write-Host "LibreSpeed CLI prepared and checksum verified."
-}
-finally {
- Remove-Item -Path $temp -Recurse -Force -ErrorAction SilentlyContinue
-}
diff --git a/tests/NetSpeed.Core.Tests/MeasurementTests.cs b/tests/NetSpeed.Core.Tests/MeasurementTests.cs
new file mode 100644
index 0000000..1e014b5
--- /dev/null
+++ b/tests/NetSpeed.Core.Tests/MeasurementTests.cs
@@ -0,0 +1,160 @@
+using NetSpeed.Core.Measurement;
+
+namespace NetSpeed.Core.Tests;
+
+public class ThroughputTrackerTests
+{
+ [Fact]
+ public void Empty_tracker_reports_zero()
+ {
+ ThroughputTracker t = new(2);
+ Assert.Equal(0, t.AverageMbps);
+ Assert.Equal(0, t.SteadyMbps);
+ Assert.Equal(0, t.CurrentMbps());
+ Assert.Equal(0, t.TotalBytes);
+ }
+
+ [Fact]
+ public void Constant_rate_gives_same_average_steady_and_current()
+ {
+ // 12.5 MB/s = 100 Mbps, sampled every 100 ms for 10 s.
+ ThroughputTracker t = new(2);
+ for (int i = 1; i <= 100; i++)
+ {
+ t.Add(i / 10d, i * 1_250_000L);
+ }
+
+ Assert.Equal(100, t.AverageMbps, 6);
+ Assert.Equal(100, t.SteadyMbps, 6);
+ Assert.Equal(100, t.CurrentMbps(), 6);
+ }
+
+ [Fact]
+ public void Steady_excludes_ramp_up()
+ {
+ // 0-2 s: slow start at 10 Mbps; 2-10 s: 900 Mbps.
+ ThroughputTracker t = new(2);
+ long bytes = 0;
+ for (int i = 1; i <= 100; i++)
+ {
+ double mbps = i <= 20 ? 10 : 900;
+ bytes += (long)(mbps * 1_000_000 / 8 / 10);
+ t.Add(i / 10d, bytes);
+ }
+
+ Assert.Equal(900, t.SteadyMbps, 3);
+ Assert.True(t.AverageMbps < t.SteadyMbps);
+ Assert.Equal(722, t.AverageMbps, 0); // (2 s × 10 + 8 s × 900) / 10 s
+ }
+
+ [Fact]
+ public void Idle_tail_after_last_byte_is_excluded()
+ {
+ // 10 s at 1000 Mbps, then 1 s with no data while waiting for the close handshake.
+ ThroughputTracker t = new(2);
+ for (int i = 1; i <= 100; i++)
+ {
+ t.Add(i / 10d, i * 12_500_000L);
+ }
+
+ for (int i = 101; i <= 110; i++)
+ {
+ t.Add(i / 10d, 100 * 12_500_000L);
+ }
+
+ Assert.Equal(1000, t.SteadyMbps, 6);
+ Assert.Equal(1000, t.AverageMbps, 6);
+ Assert.Equal(11, t.ElapsedSeconds, 6);
+ }
+
+ [Fact]
+ public void Steady_falls_back_to_average_when_too_short()
+ {
+ ThroughputTracker t = new(2);
+ t.Add(0.5, 1_000_000);
+ t.Add(1.0, 2_000_000);
+ t.Add(2.5, 5_000_000); // only 0 s after warm-up
+ Assert.Equal(t.AverageMbps, t.SteadyMbps);
+ }
+
+ [Fact]
+ public void Ignores_non_increasing_time_and_backwards_counters()
+ {
+ ThroughputTracker t = new(0);
+ t.Add(1, 1000);
+ t.Add(1, 5000); // same time: ignored
+ t.Add(0.5, 9000); // earlier: ignored
+ t.Add(2, 500); // counter went backwards: clamped to 1000
+ Assert.Equal(2, t.Count);
+ Assert.Equal(1000, t.TotalBytes);
+ }
+
+ [Fact]
+ public void Current_uses_last_window_only()
+ {
+ ThroughputTracker t = new(0);
+ t.Add(1, 1_250_000); // 10 Mbps for 1 s
+ t.Add(2, 13_750_000); // then 100 Mbps
+ Assert.Equal(100, t.CurrentMbps(1.0), 6);
+ }
+
+ [Fact]
+ public void Current_with_short_history_measures_from_phase_start()
+ {
+ ThroughputTracker t = new(0);
+ t.Add(0.2, 250_000);
+ t.Add(0.4, 500_000);
+ Assert.Equal(10, t.CurrentMbps(1.0), 6);
+ }
+}
+
+public class LatencyStatsTests
+{
+ [Fact]
+ public void Median_odd_even_empty()
+ {
+ Assert.Null(LatencyStats.Median([]));
+ Assert.Equal(3, LatencyStats.Median([5, 1, 3]));
+ Assert.Equal(2.5, LatencyStats.Median([4, 1, 2, 3]));
+ }
+
+ [Fact]
+ public void Jitter_is_mean_absolute_consecutive_difference()
+ {
+ Assert.Null(LatencyStats.Jitter([10]));
+ Assert.Equal(0, LatencyStats.Jitter([10, 10, 10]));
+ // |12-10| + |9-12| + |13-9| = 2 + 3 + 4 = 9 → 9/3
+ Assert.Equal(3, LatencyStats.Jitter([10, 12, 9, 13]));
+ }
+}
+
+public class ServerRankerTests
+{
+ [Fact]
+ public void Orders_by_rtt_and_keeps_unmeasured_last_in_original_order()
+ {
+ string[] servers = ["a", "b", "c", "d", "e"];
+ double?[] rtts = [30, null, 12, null, 12];
+ Assert.Equal(["c", "e", "a", "b", "d"], ServerRanker.Rank(servers, rtts));
+ }
+
+ [Fact]
+ public void Mismatched_lengths_throw()
+ {
+ Assert.Throws(() => ServerRanker.Rank(["a"], [1, 2]));
+ }
+}
+
+public class MessageSizerTests
+{
+ [Theory]
+ [InlineData(8192, 0, 8192)] // nothing queued yet
+ [InlineData(8192, 16 * 8192, 16384)] // exactly 1/16 → double
+ [InlineData(8192, 16 * 8192 - 1, 8192)] // just below
+ [InlineData(1 << 20, long.MaxValue, 1 << 20)] // capped
+ [InlineData(786432, 1L << 40, 1 << 20)] // doubling would exceed cap
+ public void Scales_as_in_ndt7_appendix(int current, long queued, int expected)
+ {
+ Assert.Equal(expected, MessageSizer.Next(current, queued, 1 << 20));
+ }
+}
diff --git a/tests/NetSpeed.Core.Tests/MlabParsingTests.cs b/tests/NetSpeed.Core.Tests/MlabParsingTests.cs
new file mode 100644
index 0000000..78817aa
--- /dev/null
+++ b/tests/NetSpeed.Core.Tests/MlabParsingTests.cs
@@ -0,0 +1,260 @@
+using System.Net;
+using System.Text;
+using NetSpeed.Core.Mlab;
+
+namespace NetSpeed.Core.Tests;
+
+public class LocateParserTests
+{
+ // Shape of a real Locate v2 answer for msak/throughput1 (tokens replaced, "&" escaped as in the wire JSON).
+ private const string MsakJson = """
+ {
+ "results": [
+ {
+ "machine": "mlab3-mil06.mlab-oti.measurement-lab.org",
+ "hostname": "msak-mlab3-mil06.mlab-oti.measurement-lab.org",
+ "location": { "city": "Milan", "country": "IT" },
+ "urls": {
+ "ws:///throughput/v1/download": "ws://msak-mlab3-mil06.mlab-oti.measurement-lab.org/throughput/v1/download?access_token=T1&index=0",
+ "ws:///throughput/v1/upload": "ws://msak-mlab3-mil06.mlab-oti.measurement-lab.org/throughput/v1/upload?access_token=T1&index=0",
+ "wss:///throughput/v1/download": "wss://msak-mlab3-mil06.mlab-oti.measurement-lab.org/throughput/v1/download?access_token=T1&index=0&locate_version=v2",
+ "wss:///throughput/v1/upload": "wss://msak-mlab3-mil06.mlab-oti.measurement-lab.org/throughput/v1/upload?access_token=T1&index=0&locate_version=v2"
+ }
+ },
+ {
+ "machine": "broken-1",
+ "urls": { "wss:///throughput/v1/download": "wss://x/throughput/v1/download" }
+ },
+ {
+ "machine": "insecure-1",
+ "urls": {
+ "wss:///throughput/v1/download": "ws://y/throughput/v1/download",
+ "wss:///throughput/v1/upload": "ws://y/throughput/v1/upload"
+ }
+ },
+ {
+ "machine": "mlab2-mil07.mlab-oti.measurement-lab.org",
+ "urls": {
+ "wss:///throughput/v1/download": "wss://msak-mlab2-mil07.example/throughput/v1/download?access_token=T2",
+ "wss:///throughput/v1/upload": "wss://msak-mlab2-mil07.example/throughput/v1/upload?access_token=T2"
+ }
+ }
+ ]
+ }
+ """;
+
+ [Fact]
+ public void Parses_wss_targets_in_order_and_skips_incomplete_or_insecure()
+ {
+ IReadOnlyList targets = LocateParser.Parse(MsakJson, MlabProtocol.Msak);
+
+ Assert.Equal(2, targets.Count);
+ MlabTarget first = targets[0];
+ Assert.Equal("mlab3-mil06.mlab-oti.measurement-lab.org", first.Machine);
+ Assert.Equal("msak-mlab3-mil06.mlab-oti.measurement-lab.org", first.Hostname);
+ Assert.Equal("Milan", first.City);
+ Assert.Equal("IT", first.Country);
+ Assert.Equal("wss", first.DownloadUrl.Scheme);
+ Assert.Equal("/throughput/v1/upload", first.UploadUrl.AbsolutePath);
+ Assert.Contains("access_token=T1&index=0", first.DownloadUrl.Query, StringComparison.Ordinal);
+
+ // Hostname missing → taken from the URL.
+ Assert.Equal("msak-mlab2-mil07.example", targets[1].Hostname);
+ Assert.Null(targets[1].City);
+ }
+
+ [Fact]
+ public void Ndt7_keys_are_used_for_ndt7()
+ {
+ const string json = """
+ {"results":[{"machine":"m","hostname":"ndt-m","urls":{
+ "wss:///ndt/v7/download":"wss://ndt-m/ndt/v7/download?access_token=A",
+ "wss:///ndt/v7/upload":"wss://ndt-m/ndt/v7/upload?access_token=A"}}]}
+ """;
+ Assert.Single(LocateParser.Parse(json, MlabProtocol.Ndt7));
+ Assert.Empty(LocateParser.Parse(json, MlabProtocol.Msak));
+ }
+
+ [Fact]
+ public void Invalid_json_is_a_locate_failure()
+ {
+ SpeedTestException ex = Assert.Throws(() => LocateParser.Parse("{not json", MlabProtocol.Msak));
+ Assert.Equal(SpeedTestErrorKind.LocateFailed, ex.Kind);
+ }
+
+ [Fact]
+ public void Empty_results_parse_to_empty_list()
+ {
+ Assert.Empty(LocateParser.Parse("{}", MlabProtocol.Msak));
+ Assert.Empty(LocateParser.Parse("""{"results":[]}""", MlabProtocol.Msak));
+ }
+
+ [Theory]
+ [InlineData(HttpStatusCode.NoContent, SpeedTestErrorKind.NoCapacity)]
+ [InlineData(HttpStatusCode.ServiceUnavailable, SpeedTestErrorKind.LocateFailed)]
+ [InlineData(HttpStatusCode.TooManyRequests, SpeedTestErrorKind.LocateFailed)]
+ public async Task Non_200_statuses_map_to_errors(HttpStatusCode status, SpeedTestErrorKind kind)
+ {
+ using HttpResponseMessage response = new(status);
+ SpeedTestException ex = await Assert.ThrowsAsync(
+ () => LocateClient.InterpretAsync(response, MlabProtocol.Msak, CancellationToken.None));
+ Assert.Equal(kind, ex.Kind);
+ }
+
+ [Fact]
+ public async Task Ok_without_usable_results_is_a_locate_failure()
+ {
+ using HttpResponseMessage response = new(HttpStatusCode.OK) { Content = new StringContent("""{"results":[]}""") };
+ SpeedTestException ex = await Assert.ThrowsAsync(
+ () => LocateClient.InterpretAsync(response, MlabProtocol.Msak, CancellationToken.None));
+ Assert.Equal(SpeedTestErrorKind.LocateFailed, ex.Kind);
+ }
+
+ [Fact]
+ public async Task Ok_with_results_returns_targets()
+ {
+ using HttpResponseMessage response = new(HttpStatusCode.OK) { Content = new StringContent(MsakJson) };
+ IReadOnlyList targets = await LocateClient.InterpretAsync(response, MlabProtocol.Msak, CancellationToken.None);
+ Assert.Equal(2, targets.Count);
+ }
+}
+
+public class MeasurementParserTests
+{
+ // Field set observed from a real msak-server download measurement (values shortened).
+ private const string MsakMessage = """
+ {"UUID":"mlab3-mil06_1700000000_000000000001","LocalAddr":"[2001:db8::2]:443","RemoteAddr":"203.0.113.7:51544",
+ "Application":{"BytesSent":68170045,"BytesReceived":120},"Network":{"BytesSent":68300000,"BytesReceived":900},
+ "ElapsedTime":3025520,
+ "BBRInfo":{"BW":1,"MinRTT":2},
+ "TCPInfo":{"State":1,"RTT":38905,"RTTVar":800,"MinRTT":38423,"BytesAcked":67000000,"BytesReceived":900,"ElapsedTime":3025000,"SndCwnd":1000}}
+ """;
+
+ // ndt7 spec v0.11.0 example message.
+ private const string Ndt7Message = """
+ {"AppInfo":{"ElapsedTime":1234,"NumBytes":5678},
+ "ConnectionInfo":{"Client":"1.2.3.4:5678","Server":"[::1]:2345","UUID":"abc","StartTime":"2019-07-16T15:26:05.987748459-04:00"},
+ "Origin":"server","Test":"download",
+ "TCPInfo":{"BusyTime":1,"BytesAcked":2,"BytesReceived":3,"BytesSent":4,"BytesRetrans":5,"ElapsedTime":6,"MinRTT":7000,"RTT":9000,"RTTVar":10,"RWndLimited":11,"SndBufLimited":12}}
+ """;
+
+ [Fact]
+ public void Msak_download_uses_server_bytes_sent()
+ {
+ Assert.True(MeasurementParser.TryParse(MlabProtocolKind.Msak, TestDirection.Download, Encoding.UTF8.GetBytes(MsakMessage), out ServerMeasurement m));
+ Assert.Equal(68170045, m.AppBytes);
+ Assert.Equal(3025520, m.ElapsedMicroseconds);
+ Assert.Equal(38423, m.MinRttMicroseconds);
+ Assert.Equal(38905, m.RttMicroseconds);
+ Assert.Equal("203.0.113.7", m.ClientAddress);
+ Assert.Equal("mlab3-mil06_1700000000_000000000001", m.Uuid);
+ }
+
+ [Fact]
+ public void Msak_upload_uses_server_bytes_received()
+ {
+ Assert.True(MeasurementParser.TryParse(MlabProtocolKind.Msak, TestDirection.Upload, Encoding.UTF8.GetBytes(MsakMessage), out ServerMeasurement m));
+ Assert.Equal(120, m.AppBytes);
+ }
+
+ [Fact]
+ public void Ndt7_spec_example_parses()
+ {
+ Assert.True(MeasurementParser.TryParse(MlabProtocolKind.Ndt7, TestDirection.Download, Encoding.UTF8.GetBytes(Ndt7Message), out ServerMeasurement m));
+ Assert.Equal(5678, m.AppBytes);
+ Assert.Equal(1234, m.ElapsedMicroseconds);
+ Assert.Equal(7000, m.MinRttMicroseconds);
+ Assert.Equal(9000, m.RttMicroseconds);
+ Assert.Equal("1.2.3.4", m.ClientAddress);
+ Assert.Equal("abc", m.Uuid);
+ }
+
+ [Fact]
+ public void Missing_fields_are_null_not_errors()
+ {
+ Assert.True(MeasurementParser.TryParse(MlabProtocolKind.Ndt7, TestDirection.Upload, "{}"u8, out ServerMeasurement m));
+ Assert.Null(m.AppBytes);
+ Assert.Null(m.RttMicroseconds);
+ Assert.Null(m.ClientAddress);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData("not json")]
+ [InlineData("{\"ElapsedTime\":\"x\",\"AppInfo\":{\"NumBytes\":\"text\"}}")]
+ public void Malformed_messages_are_rejected(string json)
+ {
+ Assert.False(MeasurementParser.TryParse(MlabProtocolKind.Ndt7, TestDirection.Download, Encoding.UTF8.GetBytes(json), out _));
+ Assert.False(MeasurementParser.TryParse(MlabProtocolKind.Msak, TestDirection.Download, Encoding.UTF8.GetBytes(json), out _));
+ }
+
+ [Theory]
+ [InlineData("1.2.3.4:5678", "1.2.3.4")]
+ [InlineData("[2001:db8::1]:443", "2001:db8::1")]
+ [InlineData("2001:db8::1", "2001:db8::1")]
+ [InlineData("1.2.3.4", "1.2.3.4")]
+ [InlineData("", null)]
+ [InlineData(null, null)]
+ public void StripPort(string? input, string? expected)
+ {
+ Assert.Equal(expected, AddressHelper.StripPort(input));
+ }
+}
+
+public class TestUriBuilderTests
+{
+ [Fact]
+ public void Appends_parameters_and_keeps_token()
+ {
+ Uri baseUri = new("wss://host/throughput/v1/download?access_token=abc.def&index=0");
+ Uri uri = TestUriBuilder.AddQuery(baseUri, [new("streams", "4"), new("client_name", "netspeed cmdpal")]);
+ Assert.Equal("?access_token=abc.def&index=0&streams=4&client_name=netspeed%20cmdpal", uri.Query);
+ Assert.Equal("wss", uri.Scheme);
+ Assert.Equal(443, uri.Port);
+ }
+
+ [Fact]
+ public void Never_duplicates_or_sends_empty_values()
+ {
+ Uri baseUri = new("wss://host/ndt/v7/upload?access_token=abc");
+ Uri uri = TestUriBuilder.AddQuery(baseUri, [new("access_token", "evil"), new("a", "1"), new("a", "2"), new("empty", "")]);
+ Assert.Equal("?access_token=abc&a=1", uri.Query);
+ }
+
+ [Fact]
+ public void Works_without_existing_query()
+ {
+ Uri uri = TestUriBuilder.AddQuery(new Uri("ws://localhost:8080/x"), [new("k", "v")]);
+ Assert.Equal("ws://localhost:8080/x?k=v", uri.ToString());
+ }
+}
+
+public class BuildQueryTests
+{
+ [Fact]
+ public void Msak_query_has_required_streams_and_duration_in_ms()
+ {
+ MlabEngineOptions options = new() { ClientName = "netspeed-cmdpal", ClientVersion = "0.2.0", PhaseDuration = TimeSpan.FromSeconds(10) };
+ Dictionary q = MlabEngine.BuildQuery(MlabProtocol.Msak, options, 4).ToDictionary(p => p.Key, p => p.Value);
+ Assert.Equal("4", q["streams"]);
+ Assert.Equal("10000", q["duration"]);
+ Assert.Equal("netspeed-cmdpal", q["client_name"]);
+ Assert.Equal("0.2.0", q["client_version"]);
+ }
+
+ [Fact]
+ public void Ndt7_query_has_no_msak_options()
+ {
+ List> q = [.. MlabEngine.BuildQuery(MlabProtocol.Ndt7, new MlabEngineOptions(), 1)];
+ Assert.DoesNotContain(q, p => p.Key is "streams" or "duration");
+ Assert.Equal(q.Count, q.Select(p => p.Key).Distinct().Count());
+ Assert.All(q, p => Assert.False(string.IsNullOrEmpty(p.Value)));
+ }
+
+ [Fact]
+ public void User_agent_identifies_the_client()
+ {
+ MlabEngineOptions options = new() { ClientName = "netspeed-cmdpal", ClientVersion = "0.2.0" };
+ Assert.StartsWith("netspeed-cmdpal/0.2.0 ", options.UserAgent, StringComparison.Ordinal);
+ }
+}
diff --git a/tests/NetSpeed.Core.Tests/NetSpeed.Core.Tests.csproj b/tests/NetSpeed.Core.Tests/NetSpeed.Core.Tests.csproj
new file mode 100644
index 0000000..85c099b
--- /dev/null
+++ b/tests/NetSpeed.Core.Tests/NetSpeed.Core.Tests.csproj
@@ -0,0 +1,29 @@
+
+
+
+ net10.0
+ enable
+ enable
+ false
+ true
+
+ $(NoWarn);CA1707;CA1515;CA2007;CA1861;CA1849
+
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/NetSpeed.Core.Tests/PhaseRunnerLoopbackTests.cs b/tests/NetSpeed.Core.Tests/PhaseRunnerLoopbackTests.cs
new file mode 100644
index 0000000..0d5e507
--- /dev/null
+++ b/tests/NetSpeed.Core.Tests/PhaseRunnerLoopbackTests.cs
@@ -0,0 +1,311 @@
+using System.Net;
+using System.Net.Sockets;
+using System.Net.WebSockets;
+using System.Text;
+using NetSpeed.Core.Mlab;
+
+namespace NetSpeed.Core.Tests;
+
+///
+/// Exercises the real WebSocket code against a tiny local fake server (no Internet, no M-Lab).
+/// The fake server imitates msak-server: it requires the subprotocol, streams data or reads it,
+/// sends JSON measurements and closes the connection when the duration expires.
+///
+public sealed class PhaseRunnerLoopbackTests : IAsyncDisposable
+{
+ private readonly HttpListener _listener = new();
+ private readonly CancellationTokenSource _stop = new();
+ private readonly Task _serverLoop;
+ private readonly string _prefix;
+ private int _connections;
+ private long _uploadBytesReceivedByServer;
+ private int _slowSeen;
+
+ public PhaseRunnerLoopbackTests()
+ {
+ int port = FreePort();
+ _prefix = $"http://localhost:{port}/";
+ _listener.Prefixes.Add(_prefix);
+ _listener.Start();
+ _serverLoop = Task.Run(AcceptLoopAsync);
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ await _stop.CancelAsync();
+ _listener.Stop();
+ _listener.Close();
+ try
+ {
+ await _serverLoop;
+ }
+ catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException or OperationCanceledException)
+ {
+ }
+
+ _stop.Dispose();
+ }
+
+ [Fact]
+ public async Task Download_over_several_streams_counts_bytes_and_reads_measurements()
+ {
+ List live = [];
+ PhaseResult result = await PhaseRunner.RunAsync(
+ Options(TestDirection.Download, "throughput/v1/download", streams: 3),
+ (_, mbps) => live.Add(mbps),
+ CancellationToken.None);
+
+ Assert.Equal(3, result.StreamsConnected);
+ Assert.Equal(3, Volatile.Read(ref _connections));
+ Assert.True(result.Bytes > 1_000_000, $"bytes={result.Bytes}");
+ Assert.True(result.AverageMbps > 1);
+ Assert.True(result.SteadyMbps > 1);
+ Assert.NotEmpty(live);
+ Assert.Equal("127.0.0.1", result.ClientAddress);
+ Assert.Equal(5.0, result.ServerMinRttMs);
+ Assert.Contains(6.0, result.ServerRttMs);
+ Assert.Equal(3, result.Uuids.Count);
+ }
+
+ [Fact]
+ public async Task Upload_uses_server_reported_bytes()
+ {
+ PhaseResult result = await PhaseRunner.RunAsync(
+ Options(TestDirection.Upload, "throughput/v1/upload", streams: 2),
+ null,
+ CancellationToken.None);
+
+ Assert.Equal(2, result.StreamsConnected);
+ Assert.True(result.Bytes > 100_000, $"bytes={result.Bytes}");
+
+ // The phase result must come from the server's counters, never exceed what the server read.
+ Assert.True(result.Bytes <= Interlocked.Read(ref _uploadBytesReceivedByServer));
+ }
+
+ [Fact]
+ public async Task Wrong_subprotocol_means_server_unavailable()
+ {
+ PhaseOptions options = Options(TestDirection.Download, "reject", streams: 2);
+ await Assert.ThrowsAsync(() => PhaseRunner.RunAsync(options, null, CancellationToken.None));
+ }
+
+ [Fact]
+ public async Task User_cancellation_propagates()
+ {
+ using CancellationTokenSource cts = new(TimeSpan.FromMilliseconds(400));
+ await Assert.ThrowsAnyAsync(() => PhaseRunner.RunAsync(
+ Options(TestDirection.Download, "throughput/v1/download", streams: 1, seconds: 5),
+ null,
+ cts.Token));
+ }
+
+ [Fact]
+ public async Task Fast_streams_are_measured_while_a_slow_stream_is_still_connecting()
+ {
+ System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
+ double? firstDataAt = null;
+ PhaseResult result = await PhaseRunner.RunAsync(
+ Options(TestDirection.Download, "throughput/v1/download", streams: 2, extra: [new("slowfirst", "1500")]),
+ (_, mbps) =>
+ {
+ if (mbps > 0 && firstDataAt is null)
+ {
+ firstDataAt = sw.Elapsed.TotalSeconds;
+ }
+ },
+ CancellationToken.None);
+
+ Assert.Equal(2, result.StreamsConnected);
+ Assert.NotNull(firstDataAt);
+ Assert.True(firstDataAt < 1.0, $"first data reported at {firstDataAt:0.00} s, after the slow stream's 1.5 s delay");
+ }
+
+ [Theory]
+ [InlineData(TestDirection.Download)]
+ [InlineData(TestDirection.Upload)]
+ public async Task Phase_closed_before_any_data_is_server_unavailable(TestDirection direction)
+ {
+ PhaseOptions options = Options(direction, "empty", streams: 2);
+ ServerUnavailableException ex = await Assert.ThrowsAsync(
+ () => PhaseRunner.RunAsync(options, null, CancellationToken.None));
+ Assert.Contains("before any data", ex.Message, StringComparison.Ordinal);
+ }
+
+ private PhaseOptions Options(TestDirection direction, string path, int streams, double seconds = 1.2, KeyValuePair[]? extra = null) => new()
+ {
+ Protocol = MlabProtocol.Msak,
+ Direction = direction,
+ Url = new Uri(_prefix.Replace("http://", "ws://", StringComparison.Ordinal) + path + "?access_token=test"),
+ Streams = streams,
+ Duration = TimeSpan.FromSeconds(seconds),
+ WarmupSeconds = 0.2,
+ UserAgent = "netspeed-tests/1.0",
+ Query = [new("streams", streams.ToString(System.Globalization.CultureInfo.InvariantCulture)), new("duration", "1200"), .. extra ?? []],
+ ConnectTimeout = TimeSpan.FromSeconds(5),
+ };
+
+ private static int FreePort()
+ {
+ using TcpListener l = new(IPAddress.Loopback, 0);
+ l.Start();
+ return ((IPEndPoint)l.LocalEndpoint).Port;
+ }
+
+ private async Task AcceptLoopAsync()
+ {
+ while (!_stop.IsCancellationRequested)
+ {
+ HttpListenerContext context = await _listener.GetContextAsync();
+ _ = Task.Run(() => HandleAsync(context));
+ }
+ }
+
+ private async Task HandleAsync(HttpListenerContext context)
+ {
+ string path = context.Request.Url!.AbsolutePath;
+ string? requested = context.Request.Headers["Sec-WebSocket-Protocol"];
+ if (!context.Request.IsWebSocketRequest || path == "/reject" || requested != MlabProtocol.Msak.SubProtocol
+ || context.Request.QueryString["access_token"] != "test" || context.Request.QueryString["streams"] is null)
+ {
+ context.Response.StatusCode = 400;
+ context.Response.Close();
+ return;
+ }
+
+ if (context.Request.QueryString["slowfirst"] is string slow && Interlocked.Increment(ref _slowSeen) == 1)
+ {
+ await Task.Delay(int.Parse(slow, System.Globalization.CultureInfo.InvariantCulture));
+ }
+
+ HttpListenerWebSocketContext ws = await context.AcceptWebSocketAsync(MlabProtocol.Msak.SubProtocol);
+ int id = Interlocked.Increment(ref _connections);
+ double seconds = int.Parse(context.Request.QueryString["duration"]!, System.Globalization.CultureInfo.InvariantCulture) / 1000d;
+ using WebSocket socket = ws.WebSocket;
+ try
+ {
+ if (path == "/empty")
+ {
+ // Upgrade, then close at once without sending or reading any payload.
+ await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Bye", CancellationToken.None);
+ await DrainAsync(socket);
+ }
+ else if (path.EndsWith("/download", StringComparison.Ordinal))
+ {
+ await ServeDownloadAsync(socket, id, seconds);
+ }
+ else
+ {
+ await ServeUploadAsync(socket, id, seconds);
+ }
+ }
+ catch (Exception ex) when (ex is WebSocketException or HttpListenerException or OperationCanceledException or ObjectDisposedException)
+ {
+ }
+ }
+
+ private static async Task ServeDownloadAsync(WebSocket socket, int id, double seconds)
+ {
+ byte[] chunk = new byte[64 * 1024];
+ long sent = 0;
+ DateTime start = DateTime.UtcNow;
+ DateTime nextMeasurement = start;
+ Task drain = DrainAsync(socket); // reads the client's close frame
+ while ((DateTime.UtcNow - start).TotalSeconds < seconds)
+ {
+ await socket.SendAsync(chunk, WebSocketMessageType.Binary, true, CancellationToken.None);
+ sent += chunk.Length;
+ if (DateTime.UtcNow >= nextMeasurement)
+ {
+ await SendMeasurementAsync(socket, id, sent, 0, (DateTime.UtcNow - start).TotalMicroseconds);
+ nextMeasurement = DateTime.UtcNow.AddMilliseconds(250);
+ }
+
+ await Task.Delay(2);
+ }
+
+ await SendMeasurementAsync(socket, id, sent, 0, (DateTime.UtcNow - start).TotalMicroseconds);
+ await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Done sending", CancellationToken.None);
+ await drain;
+ }
+
+ private async Task ServeUploadAsync(WebSocket socket, int id, double seconds)
+ {
+ long received = 0;
+ DateTime start = DateTime.UtcNow;
+ byte[] buffer = new byte[1 << 20];
+ using CancellationTokenSource done = new();
+
+ Task reporter = Task.Run(async () =>
+ {
+ while (!done.IsCancellationRequested && (DateTime.UtcNow - start).TotalSeconds < seconds)
+ {
+ await Task.Delay(250);
+ await SendMeasurementAsync(socket, id, 0, Interlocked.Read(ref received), (DateTime.UtcNow - start).TotalMicroseconds);
+ }
+
+ if (socket.State == WebSocketState.Open)
+ {
+ await SendMeasurementAsync(socket, id, 0, Interlocked.Read(ref received), (DateTime.UtcNow - start).TotalMicroseconds);
+ await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
+ }
+ });
+
+ while (true)
+ {
+ WebSocketReceiveResult r = await socket.ReceiveAsync(buffer, CancellationToken.None);
+ if (r.MessageType == WebSocketMessageType.Close)
+ {
+ break;
+ }
+
+ Interlocked.Add(ref received, r.Count);
+ Interlocked.Add(ref _uploadBytesReceivedByServer, r.Count); // all streams together
+ }
+
+ await done.CancelAsync();
+ try
+ {
+ await reporter;
+ }
+ catch (Exception ex) when (ex is WebSocketException or ObjectDisposedException)
+ {
+ }
+ }
+
+ private static async Task DrainAsync(WebSocket socket)
+ {
+ byte[] buffer = new byte[1024];
+ try
+ {
+ while (socket.State is WebSocketState.Open or WebSocketState.CloseSent)
+ {
+ WebSocketReceiveResult r = await socket.ReceiveAsync(buffer, CancellationToken.None);
+ if (r.MessageType == WebSocketMessageType.Close)
+ {
+ return;
+ }
+ }
+ }
+ catch (WebSocketException)
+ {
+ }
+ }
+
+ private static readonly SemaphoreSlim SendLock = new(1, 1);
+
+ private static async Task SendMeasurementAsync(WebSocket socket, int id, long bytesSent, long bytesReceived, double elapsedUs)
+ {
+ string json = string.Create(
+ System.Globalization.CultureInfo.InvariantCulture,
+ $"{{\"UUID\":\"fake-{id}\",\"RemoteAddr\":\"127.0.0.1:5{id:000}\",\"Application\":{{\"BytesSent\":{bytesSent},\"BytesReceived\":{bytesReceived}}},\"ElapsedTime\":{(long)elapsedUs},\"TCPInfo\":{{\"MinRTT\":5000,\"RTT\":6000}}}}");
+ await SendLock.WaitAsync();
+ try
+ {
+ await socket.SendAsync(Encoding.UTF8.GetBytes(json), WebSocketMessageType.Text, true, CancellationToken.None);
+ }
+ finally
+ {
+ SendLock.Release();
+ }
+ }
+}
diff --git a/tests/NetSpeed.Core.Tests/StateAndFormattingTests.cs b/tests/NetSpeed.Core.Tests/StateAndFormattingTests.cs
new file mode 100644
index 0000000..b140b53
--- /dev/null
+++ b/tests/NetSpeed.Core.Tests/StateAndFormattingTests.cs
@@ -0,0 +1,154 @@
+namespace NetSpeed.Core.Tests;
+
+internal sealed class FakeTime : TimeProvider
+{
+ public DateTimeOffset Now { get; set; } = new(2026, 11, 27, 12, 0, 0, TimeSpan.Zero);
+
+ public override DateTimeOffset GetUtcNow() => Now;
+}
+
+public sealed class LocalStateStoreTests : IDisposable
+{
+ private readonly string _dir = Path.Combine(Path.GetTempPath(), "netspeed-tests-" + Guid.NewGuid().ToString("N"));
+
+ private string StatePath => Path.Combine(_dir, "sub", "state.json");
+
+ public void Dispose()
+ {
+ if (Directory.Exists(_dir))
+ {
+ Directory.Delete(_dir, recursive: true);
+ }
+ }
+
+ [Fact]
+ public void Consent_is_absent_by_default_and_persists_once_granted()
+ {
+ FakeTime time = new();
+ LocalStateStore store = new(StatePath, time);
+ Assert.False(store.HasConsent);
+
+ store.GrantConsent();
+ Assert.True(store.HasConsent);
+ Assert.True(File.Exists(StatePath));
+
+ Assert.True(new LocalStateStore(StatePath, time).HasConsent);
+ }
+
+ [Fact]
+ public void Revoke_clears_consent()
+ {
+ LocalStateStore store = new(StatePath, new FakeTime());
+ store.GrantConsent();
+ store.RevokeConsent();
+ Assert.False(new LocalStateStore(StatePath, new FakeTime()).HasConsent);
+ }
+
+ [Fact]
+ public void Corrupt_file_means_no_consent()
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(StatePath)!);
+ File.WriteAllText(StatePath, "{ broken");
+ Assert.False(new LocalStateStore(StatePath, new FakeTime()).HasConsent);
+ }
+
+ [Fact]
+ public void Old_consent_version_asks_again()
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(StatePath)!);
+ File.WriteAllText(StatePath, """{"ConsentVersion":0,"RecentTests":[]}""");
+ Assert.False(new LocalStateStore(StatePath, new FakeTime()).HasConsent);
+ }
+
+ [Fact]
+ public void Daily_limit_is_40_in_a_rolling_24_hours()
+ {
+ FakeTime time = new();
+ LocalStateStore store = new(StatePath, time);
+
+ for (int i = 0; i < LocalStateStore.MaxTestsPerDay; i++)
+ {
+ Assert.True(store.TryRegisterTest());
+ time.Now = time.Now.AddMinutes(1);
+ }
+
+ Assert.Equal(0, store.RemainingTests);
+ Assert.False(store.TryRegisterTest());
+
+ // Survives a restart.
+ Assert.False(new LocalStateStore(StatePath, time).TryRegisterTest());
+
+ // 24 h after the first test, one slot frees up.
+ time.Now = new DateTimeOffset(2026, 11, 28, 12, 0, 0, TimeSpan.Zero);
+ Assert.Equal(1, store.RemainingTests);
+ Assert.True(store.TryRegisterTest());
+ Assert.False(store.TryRegisterTest());
+ }
+}
+
+public class SpeedResultTests
+{
+ private static SpeedResult Make(double? idle, double? down, double? up) => new()
+ {
+ EngineName = "M-Lab",
+ Protocol = "MSAK throughput1",
+ Timestamp = new DateTimeOffset(2026, 11, 27, 10, 30, 0, TimeSpan.FromHours(1)),
+ DownloadMbps = 943.21,
+ DownloadAverageMbps = 870.4,
+ UploadMbps = 48.76,
+ UploadAverageMbps = 45.1,
+ IdleLatencyMs = idle,
+ JitterMs = 1.24,
+ DownloadLoadedLatencyMs = down,
+ UploadLoadedLatencyMs = up,
+ ServerMachine = "mlab3-mil06.mlab-oti.measurement-lab.org",
+ ServerCity = "Milan",
+ ServerCountry = "IT",
+ ClientAddress = "203.0.113.7",
+ BytesReceived = 1_180_000_000,
+ BytesSent = 60_000_000,
+ Streams = 4,
+ };
+
+ [Theory]
+ [InlineData(10.0, 25.0, 80.0, 70.0, "Moderate")]
+ [InlineData(10.0, 25.0, null, 15.0, "Low")]
+ [InlineData(10.0, 200.0, 20.0, 190.0, "High")]
+ [InlineData(10.0, 5.0, null, 0.0, "Low")] // loaded below idle is clamped
+ public void Bufferbloat_is_worst_loaded_minus_idle(double idle, double? down, double? up, double expected, string grade)
+ {
+ SpeedResult r = Make(idle, down, up);
+ Assert.Equal(expected, r.BufferbloatMs!.Value, 6);
+ Assert.Equal(grade, r.BufferbloatGrade);
+ }
+
+ [Fact]
+ public void Bufferbloat_unknown_without_idle_or_loaded()
+ {
+ Assert.Null(Make(null, 30, 30).BufferbloatMs);
+ Assert.Null(Make(10, null, null).BufferbloatMs);
+ Assert.Null(Make(10, null, null).BufferbloatGrade);
+ }
+
+ [Fact]
+ public void Clipboard_text_contains_results_but_not_ip()
+ {
+ string text = ResultFormatter.ToClipboardText(Make(12.3, 40, 90));
+ Assert.Contains("Download: 943 Mbps", text, StringComparison.Ordinal);
+ Assert.Contains("Upload: 48.8 Mbps", text, StringComparison.Ordinal);
+ Assert.Contains("Idle latency: 12.3 ms • Jitter: 1.2 ms", text, StringComparison.Ordinal);
+ Assert.Contains("Bufferbloat: +78 ms (Moderate)", text, StringComparison.Ordinal);
+ Assert.Contains("Milan, IT", text, StringComparison.Ordinal);
+ Assert.Contains("MSAK throughput1, 4 stream(s)", text, StringComparison.Ordinal);
+ Assert.DoesNotContain("203.0.113.7", text, StringComparison.Ordinal);
+ }
+
+ [Theory]
+ [InlineData(0L, "0 B")]
+ [InlineData(1536L, "1.5 KiB")]
+ [InlineData(1_180_000_000L, "1.10 GiB")]
+ public void Bytes_formatting(long bytes, string expected)
+ {
+ Assert.Equal(expected, ResultFormatter.Bytes(bytes));
+ }
+}