-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
EndPointCollection.cs
234 lines (214 loc) · 8.44 KB
/
EndPointCollection.cs
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Threading.Tasks;
namespace StackExchange.Redis
{
/// <summary>
/// A list of endpoints.
/// </summary>
public sealed class EndPointCollection : Collection<EndPoint>, IEnumerable<EndPoint>
{
private static class DefaultPorts
{
public static int Standard => 6379;
public static int Ssl => 6380;
public static int Sentinel => 26379;
}
/// <summary>
/// Create a new <see cref="EndPointCollection"/>.
/// </summary>
public EndPointCollection() {}
/// <summary>
/// Create a new <see cref="EndPointCollection"/>.
/// </summary>
/// <param name="endpoints">The endpoints to add to the collection.</param>
public EndPointCollection(IList<EndPoint> endpoints) : base(endpoints) {}
/// <summary>
/// Format an <see cref="EndPoint"/>.
/// </summary>
/// <param name="endpoint">The endpoint to get a string representation for.</param>
public static string ToString(EndPoint endpoint) => Format.ToString(endpoint);
/// <summary>
/// Attempt to parse a string into an <see cref="EndPoint"/>.
/// </summary>
/// <param name="endpoint">The endpoint string to parse.</param>
public static EndPoint TryParse(string endpoint) => Format.TryParseEndPoint(endpoint);
/// <summary>
/// Adds a new endpoint to the list.
/// </summary>
/// <param name="hostAndPort">The host:port string to add an endpoint for to the collection.</param>
public void Add(string hostAndPort)
{
var endpoint = Format.TryParseEndPoint(hostAndPort);
if (endpoint == null)
{
throw new ArgumentException($"Could not parse host and port from '{hostAndPort}'", nameof(hostAndPort));
}
Add(endpoint);
}
/// <summary>
/// Adds a new endpoint to the list.
/// </summary>
/// <param name="host">The host to add.</param>
/// <param name="port">The port for <paramref name="host"/> to add.</param>
public void Add(string host, int port) => Add(Format.ParseEndPoint(host, port));
/// <summary>
/// Adds a new endpoint to the list.
/// </summary>
/// <param name="host">The host to add.</param>
/// <param name="port">The port for <paramref name="host"/> to add.</param>
public void Add(IPAddress host, int port) => Add(new IPEndPoint(host, port));
/// <summary>
/// Try adding a new endpoint to the list.
/// </summary>
/// <param name="endpoint">The endpoint to add.</param>
/// <returns><see langword="true"/> if the endpoint was added, <see langword="false"/> if not.</returns>
public bool TryAdd(EndPoint endpoint)
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
if (!Contains(endpoint))
{
base.InsertItem(Count, endpoint);
return true;
}
else
{
return false;
}
}
/// <summary>
/// See <see cref="Collection{T}.InsertItem(int, T)"/>.
/// </summary>
/// <param name="index">The index to add <paramref name="item"/> into the collection at.</param>
/// <param name="item">The item to insert at <paramref name="index"/>.</param>
protected override void InsertItem(int index, EndPoint item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
if (Contains(item))
{
throw new ArgumentException("EndPoints must be unique", nameof(item));
}
base.InsertItem(index, item);
}
/// <summary>
/// See <see cref="Collection{T}.SetItem(int, T)"/>.
/// </summary>
/// <param name="index">The index to replace an endpoint at.</param>
/// <param name="item">The item to replace the existing endpoint at <paramref name="index"/>.</param>
protected override void SetItem(int index, EndPoint item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
int existingIndex;
try
{
existingIndex = IndexOf(item);
}
catch (NullReferenceException)
{
// mono has a nasty bug in DnsEndPoint.Equals; if they do bad things here: sorry, I can't help
existingIndex = -1;
}
if (existingIndex >= 0 && existingIndex != index)
{
throw new ArgumentException("EndPoints must be unique", nameof(item));
}
base.SetItem(index, item);
}
internal void SetDefaultPorts(ServerType? serverType, bool ssl = false)
{
int defaultPort = serverType switch
{
ServerType.Sentinel => DefaultPorts.Sentinel,
_ => ssl ? DefaultPorts.Ssl : DefaultPorts.Standard,
};
for (int i = 0; i < Count; i++)
{
switch (this[i])
{
case DnsEndPoint dns when dns.Port == 0:
this[i] = new DnsEndPoint(dns.Host, defaultPort, dns.AddressFamily);
break;
case IPEndPoint ip when ip.Port == 0:
this[i] = new IPEndPoint(ip.Address, defaultPort);
break;
}
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
IEnumerator<EndPoint> IEnumerable<EndPoint>.GetEnumerator() => GetEnumerator();
/// <inheritdoc/>
public new IEnumerator<EndPoint> GetEnumerator()
{
// this does *not* need to handle all threading scenarios; but we do
// want it to at least allow overwrites of existing endpoints without
// breaking the enumerator; in particular, this avoids a problem where
// ResolveEndPointsAsync swaps the addresses on us
for (int i = 0; i < Count; i++)
{
yield return this[i];
}
}
internal bool HasDnsEndPoints()
{
foreach (var endpoint in this)
{
if (endpoint is DnsEndPoint)
{
return true;
}
}
return false;
}
internal async Task ResolveEndPointsAsync(ConnectionMultiplexer multiplexer, LogProxy log)
{
var cache = new Dictionary<string, IPAddress>(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < Count; i++)
{
if (this[i] is DnsEndPoint dns)
{
try
{
if (dns.Host == ".")
{
this[i] = new IPEndPoint(IPAddress.Loopback, dns.Port);
}
else if (cache.TryGetValue(dns.Host, out IPAddress ip))
{ // use cache
this[i] = new IPEndPoint(ip, dns.Port);
}
else
{
log?.LogInfo($"Using DNS to resolve '{dns.Host}'...");
var ips = await Dns.GetHostAddressesAsync(dns.Host).ObserveErrors().ForAwait();
if (ips.Length == 1)
{
ip = ips[0];
log?.LogInfo($"'{dns.Host}' => {ip}");
cache[dns.Host] = ip;
this[i] = new IPEndPoint(ip, dns.Port);
}
}
}
catch (Exception ex)
{
multiplexer.OnInternalError(ex);
log?.LogError(ex, ex.Message);
}
}
}
}
internal EndPointCollection Clone() => new EndPointCollection(this);
}
}