From d8aca0e7842f9b76d74ba29d1c512ba19678f5c6 Mon Sep 17 00:00:00 2001
From: elgegeto <341694139+elgegeto@users.noreply.github.com>
Date: Tue, 10 Nov 2026 16:41:06 -0300
Subject: [PATCH 1/3] perf: cache successful client memory scans briefly (#60)
Reuse extracted values for five seconds and apply missing fields from each call's own fallback. Keep missed-scan caching and force refresh intact.
---
.../MemoryScan/ClientValueScanner.cs | 86 +++++++++++--------
1 file changed, 51 insertions(+), 35 deletions(-)
diff --git a/src/RatioMaster.Core/MemoryScan/ClientValueScanner.cs b/src/RatioMaster.Core/MemoryScan/ClientValueScanner.cs
index 7ed6dc2..39c2c0d 100644
--- a/src/RatioMaster.Core/MemoryScan/ClientValueScanner.cs
+++ b/src/RatioMaster.Core/MemoryScan/ClientValueScanner.cs
@@ -20,6 +20,7 @@ public sealed partial class ClientValueScanner
/// when it runs: starting a thousand uTorrent torrents at once kept the window busy for 11 seconds.
///
internal const int MissWaitSeconds = 60;
+ internal const int HitWaitSeconds = 5;
private const int BlockSize = 64 * 1024;
@@ -27,8 +28,7 @@ public sealed partial class ClientValueScanner
private readonly ISystemClock clock;
private readonly Lock gate = new();
- /// The newest search that ended for each profile, by name: its number, and when it found nothing (null when it found the client).
- private readonly Dictionary results = new(StringComparer.Ordinal);
+ private readonly Dictionary results = new(StringComparer.Ordinal);
private long searches;
@@ -43,8 +43,8 @@ public ClientValueScanner(IProcessMemoryScanner? scanner = null, ISystemClock? c
///
/// Scans the client's process and returns the values found, or null when the client is not running,
/// the platform does not allow it, or nothing matched. fills any missing field.
- /// After a search that found nothing the client is not looked for again for
- /// seconds, unless is set: when the user asks, the client may just have started.
+ /// A recent result is reused for seconds, or
+ /// seconds when nothing was found. Explicit regeneration bypasses both waits.
///
public ClientIdentity? TryScan(ClientProfile profile, ClientIdentity fallback, Action? log = null, bool ignoreRecentMiss = false)
{
@@ -57,38 +57,56 @@ public ClientValueScanner(IProcessMemoryScanner? scanner = null, ISystemClock? c
return null;
}
- bool skip;
+ bool skipMiss = false;
+ ScanValues? cached = null;
long search = 0;
lock (this.gate)
{
- skip = !ignoreRecentMiss && this.MissedRecently(profile.Name);
- if (!skip)
+ if (!ignoreRecentMiss &&
+ this.results.TryGetValue(profile.Name, out var previous) &&
+ this.IsRecent(previous.CheckedAt, previous.Values is null ? MissWaitSeconds : HitWaitSeconds))
+ {
+ if (previous.Values is { } found)
+ {
+ cached = found;
+ }
+ else
+ {
+ skipMiss = true;
+ }
+ }
+
+ if (!skipMiss && cached is null)
{
search = ++this.searches;
}
}
- if (skip)
+ if (cached is not null)
+ {
+ return ApplyFallback(cached, fallback);
+ }
+
+ if (skipMiss)
{
log?.Invoke(string.Format(CultureInfo.CurrentCulture, Strings.ScanSkippedAfterMiss, spec.ProcessName));
return null;
}
- var identity = this.Scan(profile, spec, fallback, log);
+ var values = this.Scan(profile, spec, log);
lock (this.gate)
{
- // Searches can overlap (a start on the UI thread, Regenerate on the thread pool). The one that began last
- // saw the client last, so an older one that ends after it does not undo what it found.
+ // A newer forced scan must win even if an earlier scan finishes last.
if (!this.results.TryGetValue(profile.Name, out var newest) || newest.Search < search)
{
- this.results[profile.Name] = (search, identity is null ? this.clock.Now : null);
+ this.results[profile.Name] = (search, this.clock.Now, values);
}
}
- return identity;
+ return values is null ? null : ApplyFallback(values, fallback);
}
- private static ClientIdentity Extract(string text, ClientProfile profile, ClientIdentity fallback, Action? log)
+ private static ScanValues Extract(string text, ClientProfile profile, Action? log)
{
var peerId = Match(PeerIdRegex(), text);
var key = Match(KeyRegex(), text);
@@ -120,16 +138,18 @@ private static ClientIdentity Extract(string text, ClientProfile profile, Client
numWant = profile.DefaultNumWant.ToString(CultureInfo.InvariantCulture);
}
- return new ClientIdentity
- {
- PeerId = peerId ?? fallback.PeerId,
- Key = key ?? fallback.Key,
- Port = port ?? fallback.Port,
- NumWant = numWant ?? fallback.NumWant,
- Source = ClientIdentitySource.CopiedFromProcess,
- };
+ return new ScanValues(peerId, key, port, numWant);
}
+ private static ClientIdentity ApplyFallback(ScanValues values, ClientIdentity fallback) => new()
+ {
+ PeerId = values.PeerId ?? fallback.PeerId,
+ Key = values.Key ?? fallback.Key,
+ Port = values.Port ?? fallback.Port,
+ NumWant = values.NumWant ?? fallback.NumWant,
+ Source = ClientIdentitySource.CopiedFromProcess,
+ };
+
private static string? Match(Regex regex, string text)
{
var match = regex.Match(text);
@@ -148,7 +168,7 @@ private static ClientIdentity Extract(string text, ClientProfile profile, Client
[GeneratedRegex("&numwant=(.+?)(&| )")]
private static partial Regex NumWantRegex();
- private ClientIdentity? Scan(ClientProfile profile, ClientMemoryScanSpec spec, ClientIdentity fallback, Action? log)
+ private ScanValues? Scan(ClientProfile profile, ClientMemoryScanSpec spec, Action? log)
{
log?.Invoke(string.Format(CultureInfo.CurrentCulture, Strings.ScanLookingForProcess, spec.ProcessName));
using var session = this.scanner.Open(spec.ProcessName);
@@ -173,26 +193,22 @@ private static ClientIdentity Extract(string text, ClientProfile profile, Client
continue;
}
- var identity = Extract(text, profile, fallback, log);
+ var values = Extract(text, profile, log);
log?.Invoke(Strings.ScanSucceeded);
- return identity;
+ return values;
}
log?.Invoke(string.Format(CultureInfo.CurrentCulture, Strings.ScanFailed, profile.Name));
return null;
}
- /// Gets whether the newest search for the profile found nothing less than a minute ago. Call it inside the gate.
- private bool MissedRecently(string profileName)
+ private bool IsRecent(DateTimeOffset checkedAt, int seconds)
{
- if (!this.results.TryGetValue(profileName, out var newest) || newest.MissedAt is not { } missedAt)
- {
- return false;
- }
-
- // Measured both ways, so a clock set back since the miss does not stretch the wait.
- var since = this.clock.Now - missedAt;
- return since >= TimeSpan.Zero && since < TimeSpan.FromSeconds(MissWaitSeconds);
+ // A clock adjustment backwards should not extend a cached result.
+ var since = this.clock.Now - checkedAt;
+ return since >= TimeSpan.Zero && since < TimeSpan.FromSeconds(seconds);
}
+
+ private sealed record ScanValues(string? PeerId, string? Key, string? Port, string? NumWant);
}
}
From 6e7e965a6986eb9fd94e9e104824cbbffa4da6f4 Mon Sep 17 00:00:00 2001
From: elgegeto <341694139+elgegeto@users.noreply.github.com>
Date: Tue, 10 Nov 2026 16:41:41 -0300
Subject: [PATCH 2/3] test: cover positive scan cache, refresh, fallbacks and
1000 sequential starts
---
.../MemoryScan/ClientValueScannerTests.cs | 69 +++++++++++++++++--
1 file changed, 64 insertions(+), 5 deletions(-)
diff --git a/src/RatioMaster.Core.Tests/MemoryScan/ClientValueScannerTests.cs b/src/RatioMaster.Core.Tests/MemoryScan/ClientValueScannerTests.cs
index dce7984..3b0cf8c 100644
--- a/src/RatioMaster.Core.Tests/MemoryScan/ClientValueScannerTests.cs
+++ b/src/RatioMaster.Core.Tests/MemoryScan/ClientValueScannerTests.cs
@@ -134,19 +134,78 @@ public void AClientWhoseValuesAreNotFoundIsSearchedAgainOnlyAfterAMinute()
Assert.Equal(2, process.Opens);
}
- /// A running client's values are copied fresh for every torrent, as before.
[Fact]
- public void AClientThatWasFoundIsSearchedEveryTime()
+ public void AClientThatWasFoundIsReusedBriefly()
{
+ var clock = new FakeClock();
var process = new FakeProcessMemoryScanner(MemoryWith("&peer_id=-UT360S-abc&key=DEADBEEF&compact=1 x", padding: 0));
- var scanner = new ClientValueScanner(process, new FakeClock());
+ var scanner = new ClientValueScanner(process, clock);
var profile = Catalog.GetByName("uTorrent 3.6.0");
Assert.NotNull(scanner.TryScan(profile, Fallback));
Assert.NotNull(scanner.TryScan(profile, Fallback));
+ clock.Advance(TimeSpan.FromSeconds(ClientValueScanner.HitWaitSeconds - 1));
+ Assert.NotNull(scanner.TryScan(profile, Fallback));
+ Assert.Equal(1, process.Opens);
+
+ clock.Advance(TimeSpan.FromSeconds(1));
+ Assert.NotNull(scanner.TryScan(profile, Fallback));
Assert.Equal(2, process.Opens);
}
+ [Fact]
+ public void CachedScansPreserveEachTorrentsGeneratedFallbackFields()
+ {
+ var process = new FakeProcessMemoryScanner(MemoryWith("&peer_id=-UT360S-abc&compact=1 x", padding: 0));
+ var scanner = new ClientValueScanner(process, new FakeClock());
+ var profile = Catalog.GetByName("uTorrent 3.6.0");
+ var alternate = Fallback with { Key = "SECONDKEY", Port = "4567", NumWant = "88" };
+
+ var first = scanner.TryScan(profile, Fallback);
+ var second = scanner.TryScan(profile, alternate);
+
+ Assert.NotNull(first);
+ Assert.NotNull(second);
+ Assert.Equal("-UT360S-abc", second.PeerId);
+ Assert.Equal("FALLBACK", first.Key);
+ Assert.Equal("SECONDKEY", second.Key);
+ Assert.Equal("4567", second.Port);
+ Assert.Equal("88", second.NumWant);
+ Assert.Equal(1, process.Opens);
+ }
+
+ [Fact]
+ public void RegenerateBypassesASuccessfulCachedScan()
+ {
+ var process = new FakeProcessMemoryScanner(MemoryWith("&peer_id=-UT360S-abc&key=DEADBEEF&compact=1 x", padding: 0));
+ var scanner = new ClientValueScanner(process, new FakeClock());
+ var profile = Catalog.GetByName("uTorrent 3.6.0");
+
+ Assert.NotNull(scanner.TryScan(profile, Fallback));
+ process.CanOpen = false;
+
+ Assert.Null(scanner.TryScan(profile, Fallback, ignoreRecentMiss: true));
+ Assert.Null(scanner.TryScan(profile, Fallback));
+ Assert.Equal(2, process.Opens);
+ }
+
+ [Fact]
+ public void AThousandTorrentsOnlyScanARunningClientOnce()
+ {
+ var process = new FakeProcessMemoryScanner(MemoryWith("&peer_id=-UT360S-abc&port=54321&key=DEADBEEF&numwant=175&compact=1 x", padding: 0));
+ var scanner = new ClientValueScanner(process, new FakeClock());
+ var profile = Catalog.GetByName("uTorrent 3.6.0");
+
+ for (var i = 0; i < 1000; i++)
+ {
+ var copied = scanner.TryScan(profile, Fallback);
+ Assert.NotNull(copied);
+ Assert.Equal("-UT360S-abc", copied.PeerId);
+ }
+
+ Assert.Equal(1, process.Opens);
+ }
+
/// The user starts the client and asks for its values right away: that search cannot wait for the minute.
[Fact]
public void ASearchThatIgnoresTheRecentMissLooksAtOnceAndEndsTheWait()
@@ -160,7 +219,7 @@ public void ASearchThatIgnoresTheRecentMissLooksAtOnceAndEndsTheWait()
Assert.Null(scanner.TryScan(profile, Fallback));
Assert.Equal("-UT360S-abc", scanner.TryScan(profile, Fallback, ignoreRecentMiss: true)?.PeerId);
Assert.Equal("-UT360S-abc", scanner.TryScan(profile, Fallback)?.PeerId);
- Assert.Equal(3, process.Opens);
+ Assert.Equal(2, process.Opens);
}
[Fact]
@@ -210,7 +269,7 @@ public async Task AnOlderMissThatEndsLastDoesNotUndoANewerFind()
Assert.Null(await older);
Assert.NotNull(scanner.TryScan(profile, Fallback));
- Assert.Equal(3, client.Opens);
+ Assert.Equal(2, client.Opens);
}
/// The other way round: the client quit between two searches, and the older find that ends last does not end the wait.
From efaabcec72ee87dcbb80f8c78583604a92f19d48 Mon Sep 17 00:00:00 2001
From: elgegeto <341694139+elgegeto@users.noreply.github.com>
Date: Tue, 10 Nov 2026 16:43:17 -0300
Subject: [PATCH 3/3] test: verify 1000 factory-created torrents reuse a
successful scan
---
.../Sessions/TorrentSessionFactoryTests.cs | 23 +++++++++++++++++++
1 file changed, 23 insertions(+)
diff --git a/src/RatioMaster.Core.Tests/Sessions/TorrentSessionFactoryTests.cs b/src/RatioMaster.Core.Tests/Sessions/TorrentSessionFactoryTests.cs
index 1e71188..34afdc4 100644
--- a/src/RatioMaster.Core.Tests/Sessions/TorrentSessionFactoryTests.cs
+++ b/src/RatioMaster.Core.Tests/Sessions/TorrentSessionFactoryTests.cs
@@ -161,6 +161,29 @@ public void TorrentsStartedTogetherLookForTheClientOnceAndTheRegenerateButtonAlw
Assert.Equal(2, process.Opens);
}
+ [Fact]
+ public void StartingAThousandTorrentsUsesOneSuccessfulMemoryScan()
+ {
+ var memory = Encoding.ASCII.GetBytes(new string('.', 70_000)
+ + "GET /announce?info_hash=%aa&peer_id=-UT360S-abc123&port=54321&uploaded=0&downloaded=0&key=DEADBEEF&numwant=175&compact=1 HTTP/1.1");
+ var process = new FakeProcessMemoryScanner(memory);
+ var factory = CreateFactory(process);
+ var settings = new TorrentSettings { ClientName = "uTorrent 3.6.0" };
+
+ for (var i = 0; i < 1000; i++)
+ {
+ var hash = new byte[20];
+ System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(hash, i);
+ var session = factory.Create(Descriptor with { InfoHash = hash }, settings);
+
+ Assert.Equal(ClientIdentitySource.CopiedFromProcess, session.Identity.Source);
+ Assert.Equal("-UT360S-abc123", session.Identity.PeerId);
+ Assert.Equal("54321", session.Identity.Port);
+ }
+
+ Assert.Equal(1, process.Opens);
+ }
+
[Fact]
public void CreatesASessionForTheResolvedProfile()
{