1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
|
// <copyright file="UploadGovernor.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ This program is free software: you can redistribute it and/or modify
// │ it under the terms of the GNU Affero General Public License as published
// │ by the Free Software Foundation, version 3.
// │
// │ This program is distributed in the hope that it will be useful,
// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// │ GNU Affero General Public License for more details.
// │
// │ You should have received a copy of the GNU Affero General Public License
// │ along with this program. If not, see https://www.gnu.org/licenses/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
using Microsoft.Extensions.Options;
namespace slskd.Transfers
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using slskd.Users;
/// <summary>
/// Governs upload transfer speed.
/// </summary>
public interface IUploadGovernor
{
/// <summary>
/// Asynchronously obtains a grant of <paramref name="requestedBytes"/> for the requesting <paramref name="username"/>.
/// </summary>
/// <remarks>
/// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the
/// requested amount.
/// </remarks>
/// <param name="username">The username of the requesting user.</param>
/// <param name="requestedBytes">The number of requested bytes.</param>
/// <param name="cancellationToken">The token to monitor for cancellation.</param>
/// <returns>The operation context, including the number of bytes granted.</returns>
Task<int> GetBytesAsync(string username, int requestedBytes, CancellationToken cancellationToken);
/// <summary>
/// Returns wasted bytes for redistribution.
/// </summary>
/// <param name="username">The username of the user that generated the waste.</param>
/// <param name="attemptedBytes">The number of bytes that were attempted to be transferred.</param>
/// <param name="grantedBytes">The number of bytes granted by all governors in the system.</param>
/// <param name="actualBytes">The actual number of bytes transferred.</param>
public void ReturnBytes(string username, int attemptedBytes, int grantedBytes, int actualBytes);
}
/// <summary>
/// Governs upload transfer speed.
/// </summary>
public class UploadGovernor : IUploadGovernor
{
/// <summary>
/// Initializes a new instance of the <see cref="UploadGovernor"/> class.
/// </summary>
/// <param name="userService">The UserService instance to use.</param>
/// <param name="optionsMonitor">The OptionsMonitor instance to use.</param>
public UploadGovernor(
IUserService userService,
IOptionsMonitor<Options> optionsMonitor)
{
Users = userService;
OptionsMonitor = optionsMonitor;
OptionsMonitor.OnChange(Configure);
Configure(OptionsMonitor.CurrentValue);
}
private IOptionsMonitor<Options> OptionsMonitor { get; }
private string LastOptionsHash { get; set; }
private int LastGlobalSpeedLimit { get; set; }
private Dictionary<string, ITokenBucket> TokenBuckets { get; set; } = new Dictionary<string, ITokenBucket>();
private IUserService Users { get; }
/// <summary>
/// Asynchronously obtains a grant of <paramref name="requestedBytes"/> for the requesting <paramref name="username"/>.
/// </summary>
/// <remarks>
/// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the
/// requested amount.
/// </remarks>
/// <param name="username">The username of the requesting user.</param>
/// <param name="requestedBytes">The number of requested bytes.</param>
/// <param name="cancellationToken">The token to monitor for cancellation.</param>
/// <returns>The operation context, including the number of bytes granted.</returns>
public Task<int> GetBytesAsync(string username, int requestedBytes, CancellationToken cancellationToken)
{
var group = Users.GetGroup(username);
var bucket = TokenBuckets.GetValueOrDefault(group ?? string.Empty, TokenBuckets[Application.DefaultGroup]);
return bucket.GetAsync(requestedBytes, cancellationToken);
}
/// <summary>
/// Returns wasted bytes for redistribution.
/// </summary>
/// <param name="username">The username of the user that generated the waste.</param>
/// <param name="attemptedBytes">The number of bytes that were attempted to be transferred.</param>
/// <param name="grantedBytes">The number of bytes granted by all governors in the system.</param>
/// <param name="actualBytes">The actual number of bytes transferred.</param>
public void ReturnBytes(string username, int attemptedBytes, int grantedBytes, int actualBytes)
{
var waste = Math.Max(0, grantedBytes - actualBytes);
if (waste == 0)
{
return;
}
var group = Users.GetGroup(username);
var bucket = TokenBuckets.GetValueOrDefault(group ?? string.Empty, TokenBuckets[Application.DefaultGroup]);
// we don't have enough information to tell whether grantedBytes was reduced by the global limiter within
// Soulseek.NET, so we just return the bytes that we know for sure that were wasted, which is grantedBytes - actualBytes.
// example: we grant 1000 bytes. Soulseek.NET grants only 500. 250 bytes are written. ideally we would return 750
// bytes, but instead we return 250. this discrepancy doesn't really matter because Soulseek.NET is the constraint in
// this scenario and the additional tokens we would return would never be used.
bucket.Return(waste);
}
private void Configure(Options options)
{
static TokenBucket CreateBucket(int speedInKiB)
{
var speedInBytes = speedInKiB * 1024L;
var intervalInMs = 100;
var bucketRefreshesPerSecond = 1000 / intervalInMs;
var capacity = speedInBytes / bucketRefreshesPerSecond;
return new(capacity, interval: intervalInMs);
}
var optionsHash = Compute.Sha1Hash(options.Transfers.Groups.ToJson());
if (optionsHash == LastOptionsHash && options.Transfers.Upload.SpeedLimit == LastGlobalSpeedLimit)
{
return;
}
// build a new dictionary of token buckets based on the current groups, then
// swap it in for the existing dictionary. there's risk of inaccuracy here if
// groups are deleted or users are moved around, as bytes may be taken from or returned
// to the wrong bucket. this is acceptable. reconfiguring buckets replenishes them,
// also, so transfers in progress will briefly exceed the intended speeds.
var tokenBuckets = new Dictionary<string, ITokenBucket>()
{
{ Application.PrivilegedGroup, CreateBucket(speedInKiB: options.Transfers.Upload.SpeedLimit) },
{ Application.DefaultGroup, CreateBucket(speedInKiB: options.Transfers.Groups.Default.Upload.SpeedLimit) },
{ Application.LeecherGroup, CreateBucket(speedInKiB: options.Transfers.Groups.Leechers.Upload.SpeedLimit) },
};
foreach (var group in options.Transfers.Groups.UserDefined)
{
tokenBuckets.Add(group.Key, CreateBucket(group.Value.Upload.SpeedLimit));
}
TokenBuckets = tokenBuckets;
LastGlobalSpeedLimit = options.Transfers.Upload.SpeedLimit;
LastOptionsHash = optionsHash;
}
}
}
|