Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 64 additions & 5 deletions src/RatioMaster.Core.Tests/MemoryScan/ClientValueScannerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,19 +134,78 @@ public void AClientWhoseValuesAreNotFoundIsSearchedAgainOnlyAfterAMinute()
Assert.Equal(2, process.Opens);
}

/// <summary>A running client's values are copied fresh for every torrent, as before.</summary>
[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);
}

/// <summary>The user starts the client and asks for its values right away: that search cannot wait for the minute.</summary>
[Fact]
public void ASearchThatIgnoresTheRecentMissLooksAtOnceAndEndsTheWait()
Expand All @@ -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]
Expand Down Expand Up @@ -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);
}

/// <summary>The other way round: the client quit between two searches, and the older find that ends last does not end the wait.</summary>
Expand Down
23 changes: 23 additions & 0 deletions src/RatioMaster.Core.Tests/Sessions/TorrentSessionFactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
86 changes: 51 additions & 35 deletions src/RatioMaster.Core/MemoryScan/ClientValueScanner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ public sealed partial class ClientValueScanner
/// when it runs: starting a thousand uTorrent torrents at once kept the window busy for 11 seconds.
/// </summary>
internal const int MissWaitSeconds = 60;
internal const int HitWaitSeconds = 5;

private const int BlockSize = 64 * 1024;

private readonly IProcessMemoryScanner scanner;
private readonly ISystemClock clock;
private readonly Lock gate = new();

/// <summary>The newest search that ended for each profile, by name: its number, and when it found nothing (null when it found the client).</summary>
private readonly Dictionary<string, (long Search, DateTimeOffset? MissedAt)> results = new(StringComparer.Ordinal);
private readonly Dictionary<string, (long Search, DateTimeOffset CheckedAt, ScanValues? Values)> results = new(StringComparer.Ordinal);

private long searches;

Expand All @@ -43,8 +43,8 @@ public ClientValueScanner(IProcessMemoryScanner? scanner = null, ISystemClock? c
/// <summary>
/// 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. <paramref name="fallback"/> fills any missing field.
/// After a search that found nothing the client is not looked for again for <see cref="MissWaitSeconds"/>
/// seconds, unless <paramref name="ignoreRecentMiss"/> is set: when the user asks, the client may just have started.
/// A recent result is reused for <see cref="HitWaitSeconds"/> seconds, or <see cref="MissWaitSeconds"/>
/// seconds when nothing was found. Explicit regeneration bypasses both waits.
/// </summary>
public ClientIdentity? TryScan(ClientProfile profile, ClientIdentity fallback, Action<string>? log = null, bool ignoreRecentMiss = false)
{
Expand All @@ -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<string>? log)
private static ScanValues Extract(string text, ClientProfile profile, Action<string>? log)
{
var peerId = Match(PeerIdRegex(), text);
var key = Match(KeyRegex(), text);
Expand Down Expand Up @@ -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);
Expand All @@ -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<string>? log)
private ScanValues? Scan(ClientProfile profile, ClientMemoryScanSpec spec, Action<string>? log)
{
log?.Invoke(string.Format(CultureInfo.CurrentCulture, Strings.ScanLookingForProcess, spec.ProcessName));
using var session = this.scanner.Open(spec.ProcessName);
Expand All @@ -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;
}

/// <summary>Gets whether the newest search for the profile found nothing less than a minute ago. Call it inside the gate.</summary>
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);
}
}