| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using TeleFlow.Annotations; |
| | | 3 | | |
| | | 4 | | namespace TeleFlow.Telegram.Internal; |
| | | 5 | | |
| | | 6 | | internal sealed class MemoryTelegramChatMemberStatusCache : ITelegramChatMemberStatusCache |
| | | 7 | | { |
| | 9 | 8 | | private readonly ConcurrentDictionary<CacheKey, CacheEntry> _entries = []; |
| | | 9 | | private readonly TimeProvider _timeProvider; |
| | | 10 | | |
| | | 11 | | public MemoryTelegramChatMemberStatusCache(TimeProvider timeProvider) |
| | | 12 | | { |
| | 9 | 13 | | ArgumentNullException.ThrowIfNull(timeProvider); |
| | 9 | 14 | | _timeProvider = timeProvider; |
| | 9 | 15 | | } |
| | | 16 | | |
| | | 17 | | public ValueTask<TelegramMemberStatusSet?> GetAsync( |
| | | 18 | | long chatId, |
| | | 19 | | long userId, |
| | | 20 | | CancellationToken cancellationToken = default) |
| | | 21 | | { |
| | 10 | 22 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 23 | | |
| | 10 | 24 | | var key = new CacheKey(chatId, userId); |
| | | 25 | | |
| | 10 | 26 | | if (!_entries.TryGetValue(key, out var entry)) |
| | | 27 | | { |
| | 9 | 28 | | return ValueTask.FromResult<TelegramMemberStatusSet?>(null); |
| | | 29 | | } |
| | | 30 | | |
| | 1 | 31 | | if (entry.ExpiresAt <= _timeProvider.GetUtcNow()) |
| | | 32 | | { |
| | 0 | 33 | | _entries.TryRemove(key, out _); |
| | 0 | 34 | | return ValueTask.FromResult<TelegramMemberStatusSet?>(null); |
| | | 35 | | } |
| | | 36 | | |
| | 1 | 37 | | return ValueTask.FromResult<TelegramMemberStatusSet?>(entry.Status); |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | public ValueTask SetAsync( |
| | | 41 | | long chatId, |
| | | 42 | | long userId, |
| | | 43 | | TelegramMemberStatusSet status, |
| | | 44 | | TimeSpan ttl, |
| | | 45 | | CancellationToken cancellationToken = default) |
| | | 46 | | { |
| | 9 | 47 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 48 | | |
| | 9 | 49 | | if (!TelegramMemberStatusSetValidator.IsValid(status)) |
| | | 50 | | { |
| | 0 | 51 | | throw new ArgumentException("Telegram member status cache value must contain a known status.", nameof(status |
| | | 52 | | } |
| | | 53 | | |
| | 9 | 54 | | if (ttl <= TimeSpan.Zero) |
| | | 55 | | { |
| | 0 | 56 | | throw new ArgumentOutOfRangeException(nameof(ttl), "Telegram member status cache TTL must be greater than ze |
| | | 57 | | } |
| | | 58 | | |
| | 9 | 59 | | var key = new CacheKey(chatId, userId); |
| | 9 | 60 | | var entry = new CacheEntry(status, _timeProvider.GetUtcNow().Add(ttl)); |
| | 9 | 61 | | _entries[key] = entry; |
| | 9 | 62 | | return ValueTask.CompletedTask; |
| | | 63 | | } |
| | | 64 | | |
| | | 65 | | private readonly record struct CacheKey(long ChatId, long UserId); |
| | | 66 | | |
| | | 67 | | private readonly record struct CacheEntry(TelegramMemberStatusSet Status, DateTimeOffset ExpiresAt); |
| | | 68 | | } |