-
Notifications
You must be signed in to change notification settings - Fork 11
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
commands cooldowns using load factors #280
Open
Felk
wants to merge
3
commits into
master
Choose a base branch
from
commands_cooldowns
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,16 +5,27 @@ | |
using System.Linq; | ||
using System.Threading.Tasks; | ||
using Microsoft.Extensions.Logging; | ||
using NodaTime; | ||
using TPP.ArgsParsing; | ||
using TPP.Core.Utils; | ||
using TPP.Model; | ||
using TPP.Persistence; | ||
|
||
namespace TPP.Core.Commands | ||
{ | ||
public interface ICommandProcessor | ||
{ | ||
public Task<CommandResult?> Process(string commandName, IImmutableList<string> args, Message message); | ||
public Command? FindCommand(string commandName); | ||
public void InstallCommand(Command command); | ||
public void UninstallCommand(params string[] commandOrAlias); | ||
} | ||
|
||
/// <summary> | ||
/// The command processor can be configured using <see cref="Command"/> instances to have commands, | ||
/// which then get executed using the <see cref="CommandProcessor.Process"/> method. | ||
/// </summary> | ||
public class CommandProcessor | ||
public class CommandProcessor : ICommandProcessor | ||
{ | ||
/// <summary> | ||
/// maximum execution time for a command before a warning is logged. | ||
|
@@ -24,16 +35,45 @@ public class CommandProcessor | |
private readonly ILogger<CommandProcessor> _logger; | ||
private readonly ICommandLogger _commandLogger; | ||
private readonly ArgsParser _argsParser; | ||
private readonly IClock _clock; | ||
|
||
private readonly Dictionary<string, Command> _commands = new(); | ||
|
||
private readonly float _maxLoadFactor; | ||
private readonly Duration _maxLoadFactorTimeframe; | ||
private readonly float _additionalLoadFactorAtHighThreshold; | ||
private Dictionary<User, TtlQueue<float>> _loadsPerUser = new(); | ||
|
||
/// <summary> | ||
/// Create a new command processor instance | ||
/// </summary> | ||
/// <param name="logger">logger</param> | ||
/// <param name="commandLogger">command logger</param> | ||
/// <param name="argsParser">args parser instance</param> | ||
/// <param name="clock">clock</param> | ||
/// <param name="maxLoadFactor">maximum load factor before commands are silently dropped</param> | ||
/// <param name="maxLoadFactorTimeframe">timeframe for which the load factor is computed</param> | ||
/// <param name="additionalLoadFactorAtHighThreshold"> | ||
/// additional load to add to the load factor when a user is at their maximum load capacity. | ||
/// It is linearly interpolated from 0 when there are no messages within the timeframe, | ||
/// up to the supplied number multiplier when at the maximum amount of messages within the timeframe. | ||
/// This is to have the load factor be more effective against continuous spam than sporadic bursts.</param> | ||
public CommandProcessor( | ||
ILogger<CommandProcessor> logger, | ||
ICommandLogger commandLogger, | ||
ArgsParser argsParser) | ||
ArgsParser argsParser, | ||
IClock clock, | ||
float maxLoadFactor = 200f, | ||
Duration? maxLoadFactorTimeframe = null, | ||
float additionalLoadFactorAtHighThreshold = 2f) | ||
{ | ||
_logger = logger; | ||
_commandLogger = commandLogger; | ||
_argsParser = argsParser; | ||
_clock = clock; | ||
_maxLoadFactor = maxLoadFactor; | ||
_maxLoadFactorTimeframe = maxLoadFactorTimeframe ?? Duration.FromMinutes(10); | ||
_additionalLoadFactorAtHighThreshold = additionalLoadFactorAtHighThreshold; | ||
} | ||
|
||
public void InstallCommand(Command command) | ||
|
@@ -69,8 +109,34 @@ public void UninstallCommand(params string[] commandOrAlias) | |
public Command? FindCommand(string commandName) => | ||
_commands.TryGetValue(commandName.ToLower(), out Command command) ? command : null; | ||
|
||
private float CheckAndUpdateLoadFactorForUser(User user) | ||
{ | ||
_loadsPerUser = _loadsPerUser | ||
.Where(kvp => kvp.Value.Count > 0) | ||
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); | ||
if (!_loadsPerUser.TryGetValue(user, out TtlQueue<float>? loads)) | ||
{ | ||
loads = new TtlQueue<float>(_maxLoadFactorTimeframe, _clock); | ||
_loadsPerUser[user] = loads; | ||
} | ||
float sum = loads.Sum(); | ||
float ratioFilled = Math.Min(1, sum / _maxLoadFactor); | ||
float toAdd = 1 + ratioFilled * _additionalLoadFactorAtHighThreshold; | ||
loads.Enqueue(toAdd); | ||
return sum + toAdd; | ||
} | ||
|
||
public async Task<CommandResult?> Process(string commandName, IImmutableList<string> args, Message message) | ||
{ | ||
float loadFactor = CheckAndUpdateLoadFactorForUser(message.User); | ||
if (loadFactor > _maxLoadFactor) | ||
{ | ||
_logger.LogDebug( | ||
"command '{Command}' from user {User} ignored because load factor is {LoadFactor} " + | ||
"for timeframe {Duration}, which is above the maximum of {MaxLoadFactor}", | ||
commandName, message.User, loadFactor, _maxLoadFactorTimeframe, _maxLoadFactor); | ||
return new CommandResult(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Return some feedback to the user to let them know they are spamming too hard. I think the natural reaction to your command not being processed is to try again, which may lead to users just digging themselves into a deeper hole and frustrate nonmalicious users. |
||
} | ||
if (!_commands.TryGetValue(commandName.ToLower(), out Command command)) | ||
{ | ||
_logger.LogDebug("unknown command '{Command}'", commandName); | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These can be moved to class constants, E.G. DefaultMaxLoadFactor, ...
this should provide (marginally) easier fine-tuning when the time comes