Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: download limiter #1003

Closed
wants to merge 3 commits into from
Closed
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
1 change: 1 addition & 0 deletions src/Starward/Pages/Setting/DownloadSettingPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
Spacing="12">
<NumberBox MinWidth="100"
Minimum="0"
Maximum="2097151"
Value="{x:Bind SpeedLimit, Mode=TwoWay}" />
<TextBlock VerticalAlignment="Center" Text="KB/s" />
</StackPanel>
Expand Down
11 changes: 10 additions & 1 deletion src/Starward/Pages/Setting/DownloadSettingPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Starward.Services.Download;
using System;
using System.IO;
using System.Threading.RateLimiting;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.System;
Expand Down Expand Up @@ -69,7 +70,15 @@ partial void OnDefaultInstallPathChanged(string? value)
private int speedLimit = AppConfig.SpeedLimitKBPerSecond;
partial void OnSpeedLimitChanged(int value)
{
InstallGameManager.SpeedLimitBytesPerSecond = value == 0 ? long.MaxValue : value * 1024;
InstallGameManager.SpeedLimitBytesPerSecond = value <= 0 ? int.MaxValue : value * 1024;
InstallGameManager.rateLimiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions
{
TokensPerPeriod = InstallGameManager.SpeedLimitBytesPerPeriod,
ReplenishmentPeriod = InstallGameManager.SpeedLimitReplenishmentPeriod,
TokenLimit = InstallGameManager.SpeedLimitBytesPerPeriod,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
AutoReplenishment = true
});
AppConfig.SpeedLimitKBPerSecond = value;
}

Expand Down
25 changes: 20 additions & 5 deletions src/Starward/Services/Download/InstallGameManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.RateLimiting;

namespace Starward.Services.Download;

Expand All @@ -20,8 +20,15 @@ internal class InstallGameManager
private InstallGameManager()
{
_services = new();
long speed = AppConfig.SpeedLimitKBPerSecond * 1024;
SpeedLimitBytesPerSecond = speed == 0 ? long.MaxValue : speed;
int speed = AppConfig.SpeedLimitKBPerSecond * 1024;
rateLimiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions
{
TokensPerPeriod = SpeedLimitBytesPerPeriod,
ReplenishmentPeriod = SpeedLimitReplenishmentPeriod,
TokenLimit = SpeedLimitBytesPerPeriod,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
AutoReplenishment = true
});
}


Expand All @@ -33,10 +40,18 @@ private InstallGameManager()
public static long DownloadBytesInSecond;


public static long SpeedLimitBytesPerSecond { get; set; }
public static int SpeedLimitBytesPerSecond { get; set; }


public static int SpeedLimitBytesPerPeriod => Math.Max((int)Math.Floor((double)SpeedLimitBytesPerSecond / 40), 1 << 14);


// 25: 将每秒切割为上面的40份,间隔越小速度越精准。
// 因为buffer较小,间隔极小的话请求令牌的速度将大于补充令牌逻辑运行的时间,导致无论限速多少实际速度只会在1MB/s左右。
public static TimeSpan SpeedLimitReplenishmentPeriod => SpeedLimitBytesPerPeriod == 1 << 14 ? TimeSpan.FromSeconds((1 << 14) / (double)SpeedLimitBytesPerSecond) : TimeSpan.FromMilliseconds(25);


public static bool IsExceedSpeedLimit => Interlocked.Read(ref DownloadBytesInSecond) >= SpeedLimitBytesPerSecond;
public static TokenBucketRateLimiter rateLimiter;


private long _lastTimeStamp;
Expand Down
15 changes: 9 additions & 6 deletions src/Starward/Services/Download/InstallGameService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
using System.Text;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.RateLimiting;
using System.Threading.Tasks;
using Vanara.PInvoke;

Expand Down Expand Up @@ -1203,14 +1204,16 @@ protected async Task DownloadItemAsync(InstallGameItem item, CancellationToken c
int length;
while ((length = await hs.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) != 0)
{
RateLimitLease lease;
if (InstallGameManager.SpeedLimitBytesPerSecond != int.MaxValue)
do
{
lease = await InstallGameManager.rateLimiter.AcquireAsync(length, cancellationToken).ConfigureAwait(false);
if (!lease.IsAcquired)
await Task.Delay(1, cancellationToken).ConfigureAwait(false);
} while (!lease.IsAcquired);
await fs.WriteAsync(buffer.AsMemory(0, length), cancellationToken).ConfigureAwait(false);
Interlocked.Add(ref _finishBytes, length);
Interlocked.Add(ref InstallGameManager.DownloadBytesInSecond, length);
if (InstallGameManager.IsExceedSpeedLimit)
{
long t = Stopwatch.GetTimestamp() / (Stopwatch.Frequency / 1000) % 1000;
await Task.Delay((int)(1000 - t), cancellationToken);
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/Starward/Starward.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Starward.Assets" Version="0.4.13" />
<PackageReference Include="Starward.NativeLib" Version="0.2.1" />
<PackageReference Include="System.Threading.RateLimiting" Version="8.0.0" />
<PackageReference Include="Vanara.PInvoke.ComCtl32" Version="4.0.2" />
<PackageReference Include="Vanara.PInvoke.DwmApi" Version="4.0.2" />
<PackageReference Include="Vanara.PInvoke.Ole" Version="4.0.2" />
Expand Down
Loading