37 lines
1.3 KiB
C#
37 lines
1.3 KiB
C#
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)
|
|
{
|
|
if (!_store.ContainsKey(session))
|
|
{
|
|
_store[session] = new();
|
|
}
|
|
_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);
|
|
|
|
/// <inheritdoc />
|
|
public Task<bool> ClearAsync(CompositeSessionKey session, CancellationToken ct)
|
|
=> Task.FromResult(_store.TryRemove(session, out _));
|
|
} |