This commit is contained in:
32
BotPages.Core/Storage/InMemoryStateStorage.cs
Normal file
32
BotPages.Core/Storage/InMemoryStateStorage.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using BotPages.Core.Abstractions;
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace BotPages.Core.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Памятное хранилище состояния.
|
||||
/// </summary>
|
||||
public sealed class InMemoryStateStorage : IStateStorage
|
||||
{
|
||||
private readonly ConcurrentDictionary<CompositeSessionKey, ConcurrentDictionary<string, object?>> _store = new();
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<T?> GetAsync<T>(CompositeSessionKey session, string key, CancellationToken ct)
|
||||
=> Task.FromResult(_store.TryGetValue(session, out var dict) ?
|
||||
dict.TryGetValue(key, out var obj) ? (T?)obj : default
|
||||
: default);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task SetAsync<T>(CompositeSessionKey session, string key, T state, CancellationToken ct)
|
||||
{
|
||||
_store[session][key] = state!;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<bool> RemoveAsync(CompositeSessionKey session, string key, CancellationToken ct)
|
||||
=> Task.FromResult(_store.TryGetValue(session, out var dict) ? dict.TryRemove(key, out _) : true);
|
||||
|
||||
public Task<bool> ClearAsync(CompositeSessionKey session, CancellationToken ct)
|
||||
=> Task.FromResult(_store.TryRemove(session, out _));
|
||||
}
|
||||
Reference in New Issue
Block a user