forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClusterStateCache.cs
More file actions
67 lines (57 loc) · 2.86 KB
/
ClusterStateCache.cs
File metadata and controls
67 lines (57 loc) · 2.86 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
using Npgsql.Util;
using System;
using System.Collections.Concurrent;
namespace Npgsql
{
static class ClusterStateCache
{
static readonly ConcurrentDictionary<ClusterIdentifier, ClusterInfo> Clusters = new();
internal static ClusterState GetClusterState(string host, int port, bool ignoreExpiration)
=> Clusters.TryGetValue(new(host, port), out var cs) && (ignoreExpiration || !cs.Timeout.HasExpired)
? cs.State
: ClusterState.Unknown;
#if NETSTANDARD2_0
internal static ClusterState UpdateClusterState(string host, int port, ClusterState state, DateTime timeStamp, TimeSpan stateExpiration)
=> Clusters.AddOrUpdate(
new ClusterIdentifier(host, port),
new ClusterInfo(state, new NpgsqlTimeout(stateExpiration), timeStamp),
(_, oldInfo) => oldInfo.TimeStamp >= timeStamp ? oldInfo : new ClusterInfo(state, new NpgsqlTimeout(stateExpiration), timeStamp)).State;
#else
internal static ClusterState UpdateClusterState(string host, int port, ClusterState state, DateTime timeStamp, TimeSpan stateExpiration)
=> Clusters.AddOrUpdate(
new ClusterIdentifier(host, port),
(_, newInfo) => newInfo,
(_, oldInfo, newInfo) => oldInfo.TimeStamp >= newInfo.TimeStamp ? oldInfo : newInfo,
new ClusterInfo(state, new NpgsqlTimeout(stateExpiration), timeStamp)).State;
#endif
internal static void RemoveClusterState(string host, int port)
=> Clusters.TryRemove(new ClusterIdentifier(host, port), out _);
internal static void Clear() => Clusters.Clear();
readonly struct ClusterIdentifier : IEquatable<ClusterIdentifier>
{
readonly string _host;
readonly int _port;
public ClusterIdentifier(string host, int port) => (_host, _port) = (host, port);
public override bool Equals(object? obj) => obj is ClusterIdentifier other && Equals(other);
public bool Equals(ClusterIdentifier other) => _port == other._port && _host == other._host;
public override int GetHashCode() => HashCode.Combine(_host, _port);
}
readonly struct ClusterInfo
{
internal readonly ClusterState State;
internal readonly NpgsqlTimeout Timeout;
// While the TimeStamp is not strictly required, it does lower the risk of overwriting the current state with an old value
internal readonly DateTime TimeStamp;
public ClusterInfo(ClusterState state, NpgsqlTimeout timeout, DateTime timeStamp)
=> (State, Timeout, TimeStamp) = (state, timeout, timeStamp);
}
}
enum ClusterState : byte
{
Unknown = 0,
Offline = 1,
PrimaryReadWrite = 2,
PrimaryReadOnly = 3,
Standby = 4
}
}