//
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ 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
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
//
using Microsoft.Extensions.Options;
namespace slskd.Transfers
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using slskd.Users;
///
/// Governs upload transfer speed.
///
public interface IUploadGovernor
{
///
/// Asynchronously obtains a grant of for the requesting .
///
///
/// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the
/// requested amount.
///
/// The username of the requesting user.
/// The number of requested bytes.
/// The token to monitor for cancellation.
/// The operation context, including the number of bytes granted.
Task GetBytesAsync(string username, int requestedBytes, CancellationToken cancellationToken);
///
/// Returns wasted bytes for redistribution.
///
/// The username of the user that generated the waste.
/// The number of bytes that were attempted to be transferred.
/// The number of bytes granted by all governors in the system.
/// The actual number of bytes transferred.
public void ReturnBytes(string username, int attemptedBytes, int grantedBytes, int actualBytes);
}
///
/// Governs upload transfer speed.
///
public class UploadGovernor : IUploadGovernor
{
///
/// Initializes a new instance of the class.
///
/// The UserService instance to use.
/// The OptionsMonitor instance to use.
public UploadGovernor(
IUserService userService,
IOptionsMonitor optionsMonitor)
{
Users = userService;
OptionsMonitor = optionsMonitor;
OptionsMonitor.OnChange(Configure);
Configure(OptionsMonitor.CurrentValue);
}
private IOptionsMonitor OptionsMonitor { get; }
private string LastOptionsHash { get; set; }
private int LastGlobalSpeedLimit { get; set; }
private Dictionary TokenBuckets { get; set; } = new Dictionary();
private IUserService Users { get; }
///
/// Asynchronously obtains a grant of for the requesting .
///
///
/// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the
/// requested amount.
///
/// The username of the requesting user.
/// The number of requested bytes.
/// The token to monitor for cancellation.
/// The operation context, including the number of bytes granted.
public Task 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);
}
///
/// Returns wasted bytes for redistribution.
///
/// The username of the user that generated the waste.
/// The number of bytes that were attempted to be transferred.
/// The number of bytes granted by all governors in the system.
/// The actual number of bytes transferred.
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()
{
{ 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;
}
}
}