| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using TeleFlow.Framework.States; |
| | | 3 | | |
| | | 4 | | namespace TeleFlow.Storage.Memory; |
| | | 5 | | |
| | | 6 | | public sealed class MemoryStateDataStore : IStateDataStore |
| | | 7 | | { |
| | 37 | 8 | | private readonly ConcurrentDictionary<StateDataKey, string> _data = new(); |
| | | 9 | | |
| | | 10 | | public ValueTask<string?> GetDataAsync( |
| | | 11 | | StateKey key, |
| | | 12 | | string dataKey, |
| | | 13 | | CancellationToken cancellationToken = default) |
| | | 14 | | { |
| | 33 | 15 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 32 | 16 | | ValidateDataKey(dataKey); |
| | | 17 | | |
| | 30 | 18 | | _data.TryGetValue(new StateDataKey(key, dataKey), out var value); |
| | 30 | 19 | | return ValueTask.FromResult(value); |
| | | 20 | | } |
| | | 21 | | |
| | | 22 | | public ValueTask SetDataAsync( |
| | | 23 | | StateKey key, |
| | | 24 | | string dataKey, |
| | | 25 | | string value, |
| | | 26 | | CancellationToken cancellationToken = default) |
| | | 27 | | { |
| | 20 | 28 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 19 | 29 | | ValidateDataKey(dataKey); |
| | 17 | 30 | | ArgumentNullException.ThrowIfNull(value); |
| | | 31 | | |
| | 16 | 32 | | _data[new StateDataKey(key, dataKey)] = value; |
| | 16 | 33 | | return ValueTask.CompletedTask; |
| | | 34 | | } |
| | | 35 | | |
| | | 36 | | public ValueTask RemoveDataAsync( |
| | | 37 | | StateKey key, |
| | | 38 | | string dataKey, |
| | | 39 | | CancellationToken cancellationToken = default) |
| | | 40 | | { |
| | 5 | 41 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 4 | 42 | | ValidateDataKey(dataKey); |
| | | 43 | | |
| | 2 | 44 | | _data.TryRemove(new StateDataKey(key, dataKey), out _); |
| | 2 | 45 | | return ValueTask.CompletedTask; |
| | | 46 | | } |
| | | 47 | | |
| | | 48 | | public ValueTask ClearDataAsync( |
| | | 49 | | StateKey key, |
| | | 50 | | CancellationToken cancellationToken = default) |
| | | 51 | | { |
| | 10 | 52 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 53 | | |
| | 36 | 54 | | foreach (var candidate in _data.Keys) |
| | | 55 | | { |
| | 9 | 56 | | if (candidate.StateKey == key) |
| | | 57 | | { |
| | 8 | 58 | | _data.TryRemove(candidate, out _); |
| | | 59 | | } |
| | | 60 | | } |
| | | 61 | | |
| | 9 | 62 | | return ValueTask.CompletedTask; |
| | | 63 | | } |
| | | 64 | | |
| | | 65 | | private static void ValidateDataKey(string dataKey) |
| | | 66 | | { |
| | 55 | 67 | | ArgumentException.ThrowIfNullOrWhiteSpace(dataKey); |
| | 49 | 68 | | } |
| | | 69 | | |
| | | 70 | | private readonly record struct StateDataKey(StateKey StateKey, string DataKey); |
| | | 71 | | } |