-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInMemoryEndpointStateStore.cs
More file actions
91 lines (77 loc) · 2.68 KB
/
InMemoryEndpointStateStore.cs
File metadata and controls
91 lines (77 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using ApiHealthDashboard.Configuration;
using ApiHealthDashboard.Domain;
namespace ApiHealthDashboard.State;
public sealed class InMemoryEndpointStateStore : IEndpointStateStore
{
private readonly object _syncRoot = new();
private readonly Dictionary<string, EndpointState> _states = new(StringComparer.OrdinalIgnoreCase);
public InMemoryEndpointStateStore(IEnumerable<EndpointConfig> endpoints)
{
Initialize(endpoints);
}
public IReadOnlyCollection<EndpointState> GetAll()
{
lock (_syncRoot)
{
return _states.Values
.Select(static state => state.Clone())
.OrderBy(static state => state.EndpointName, StringComparer.OrdinalIgnoreCase)
.ThenBy(static state => state.EndpointId, StringComparer.OrdinalIgnoreCase)
.ToArray();
}
}
public EndpointState? Get(string endpointId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(endpointId);
lock (_syncRoot)
{
return _states.TryGetValue(endpointId, out var state)
? state.Clone()
: null;
}
}
public void Upsert(EndpointState state)
{
ArgumentNullException.ThrowIfNull(state);
ArgumentException.ThrowIfNullOrWhiteSpace(state.EndpointId);
lock (_syncRoot)
{
_states[state.EndpointId] = state.Clone();
}
}
public void Initialize(IEnumerable<EndpointConfig> endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
lock (_syncRoot)
{
var existingStates = new Dictionary<string, EndpointState>(_states, StringComparer.OrdinalIgnoreCase);
_states.Clear();
foreach (var endpoint in endpoints)
{
if (endpoint is null || string.IsNullOrWhiteSpace(endpoint.Id))
{
continue;
}
if (existingStates.TryGetValue(endpoint.Id, out var existingState))
{
var preservedState = existingState.Clone();
preservedState.EndpointId = endpoint.Id;
preservedState.EndpointName = endpoint.Name;
_states[endpoint.Id] = preservedState;
continue;
}
_states[endpoint.Id] = CreateInitialState(endpoint);
}
}
}
private static EndpointState CreateInitialState(EndpointConfig endpoint)
{
return new EndpointState
{
EndpointId = endpoint.Id,
EndpointName = endpoint.Name,
Status = "Unknown",
IsPolling = false
};
}
}