|
| 1 | +using System; |
| 2 | +using System.Threading; |
| 3 | +using System.Threading.Tasks; |
| 4 | +using Microsoft.Extensions.Options; |
| 5 | +using Orleans; |
| 6 | +using Turbo.Games.Configuration; |
| 7 | +using Turbo.Primitives.Game.Enums; |
| 8 | +using Turbo.Primitives.Game.Grains; |
| 9 | +using Turbo.Primitives.Orleans; |
| 10 | + |
| 11 | +namespace Turbo.Games.Grains; |
| 12 | + |
| 13 | +internal sealed class SnowWarInputGrain : Grain, ISnowWarInputGrain |
| 14 | +{ |
| 15 | + private static readonly TimeSpan InputWindow = TimeSpan.FromSeconds(1); |
| 16 | + |
| 17 | + private readonly SnowWarConfig _config; |
| 18 | + private readonly IGrainFactory _grainFactory; |
| 19 | + private readonly TimeProvider _time; |
| 20 | + |
| 21 | + private readonly SnowWarInputLiveState _state; |
| 22 | + |
| 23 | + public SnowWarInputGrain( |
| 24 | + IOptions<SnowWarConfig> config, |
| 25 | + IGrainFactory grainFactory, |
| 26 | + TimeProvider time |
| 27 | + ) |
| 28 | + { |
| 29 | + _config = config.Value; |
| 30 | + _grainFactory = grainFactory; |
| 31 | + _time = time; |
| 32 | + |
| 33 | + _state = new() { PlayerId = this.GetPlayerId() }; |
| 34 | + } |
| 35 | + |
| 36 | + public async Task QueueInputAsync( |
| 37 | + SnowWarInput input, |
| 38 | + int[] values, |
| 39 | + int turn, |
| 40 | + int subturn, |
| 41 | + CancellationToken ct |
| 42 | + ) |
| 43 | + { |
| 44 | + if (!TryAdmit() || await GameAsync(ct) is not { } game) |
| 45 | + return; |
| 46 | + |
| 47 | + await game.QueueInputAsync(_state.PlayerId, input, values, turn, subturn, ct); |
| 48 | + } |
| 49 | + |
| 50 | + public async Task RequestFullStatusAsync(CancellationToken ct) |
| 51 | + { |
| 52 | + if (!TryAdmit() || await GameAsync(ct) is not { } game) |
| 53 | + return; |
| 54 | + |
| 55 | + await game.RequestFullStatusAsync(_state.PlayerId, ct); |
| 56 | + } |
| 57 | + |
| 58 | + private bool TryAdmit() |
| 59 | + { |
| 60 | + var now = _time.GetUtcNow(); |
| 61 | + |
| 62 | + if (now - _state.WindowStartedAt >= InputWindow) |
| 63 | + { |
| 64 | + _state.WindowStartedAt = now; |
| 65 | + _state.InputsInWindow = 0; |
| 66 | + } |
| 67 | + |
| 68 | + if (_state.InputsInWindow >= _config.MaxInputsPerSecond) |
| 69 | + return false; |
| 70 | + |
| 71 | + _state.InputsInWindow++; |
| 72 | + |
| 73 | + return true; |
| 74 | + } |
| 75 | + |
| 76 | + private async Task<ISnowWarGameGrain?> GameAsync(CancellationToken ct) |
| 77 | + { |
| 78 | + var gameId = await _grainFactory |
| 79 | + .GetSnowWarDirectoryGrain() |
| 80 | + .GetGameIdOfPlayerAsync(_state.PlayerId, ct); |
| 81 | + |
| 82 | + return gameId is { } id ? _grainFactory.GetSnowWarGameGrain(id) : null; |
| 83 | + } |
| 84 | +} |
0 commit comments