-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionString.cs
More file actions
316 lines (270 loc) · 8.84 KB
/
ConnectionString.cs
File metadata and controls
316 lines (270 loc) · 8.84 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
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#region License
/* ************************************************************
*
* @author Couchbase <info@couchbase.com>
* @copyright 2025 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ************************************************************/
#endregion
using System.Text;
using System.Text.RegularExpressions;
using Couchbase.AnalyticsClient.Internal.Utils;
using Couchbase.AnalyticsClient.Utils;
namespace Couchbase.AnalyticsClient.Internal;
internal class ConnectionString
{
private const int HttpsPort = 443;
private const int HttpPort = 80;
private const string ExecuteQueryPath = "api/v1/request";
private static readonly Regex ConnectionStringRegex = new Regex(
"^((?<scheme>[^://]+)://)?((?<username>[^\n@]+)@)?(?<hosts>[^\n?]+)?(\\?(?<params>(.+)))?",
RegexOptions.Compiled | RegexOptions.CultureInvariant
);
private static readonly Regex Ipv6Regex = new Regex(
"^\\[(?<address>.+)](:?(?<port>[0-9]+))?$",
RegexOptions.Compiled | RegexOptions.CultureInvariant
);
public Scheme Scheme { get; private set; } = Scheme.Http;
public string? Username { get; private set; }
public IList<HostEndpoint> Hosts { get; private set; } = new List<HostEndpoint>();
public IDictionary<string, string> Parameters { get; private set; } = new Dictionary<string, string>();
/// <summary>
/// Gets or sets a value that determines whether host names are provided in random order during bootstrapping. (default: false)
/// </summary>
/// <remarks>The RFC specifies that hosts should be used in random order, but the existing behavior is serial.</remarks>
public bool RandomizeSeedHosts { get; set; } = false;
private ConnectionString()
{
}
internal static ConnectionString Parse(string input)
{
ArgumentNullException.ThrowIfNull(input);
var match = ConnectionStringRegex.Match(input);
if (!match.Success)
{
throw new ArgumentException("Invalid connection string");
}
var connectionString = new ConnectionString();
if (match.Groups["scheme"].Success)
{
connectionString.Scheme = match.Groups["scheme"].Value switch
{
"http" => Scheme.Http,
"https" => Scheme.Https,
_ => throw new ArgumentException($"Unknown scheme {match.Groups["scheme"].Value}")
};
}
if (match.Groups["username"].Success)
{
connectionString.Username = match.Groups["username"].Value;
}
if (match.Groups["hosts"].Success)
{
connectionString.Hosts = match.Groups["hosts"].Value.Split(',')
.Select(host => HostEndpoint.Parse(host.Trim()))
.ToList();
} else if (match.Groups["hosts"].Length == 0)
{
throw new ArgumentException("Hosts list is empty. At least one host is expected in the connection string.");
}
if (match.Groups["params"].Success)
{
connectionString.Parameters = match.Groups["params"].Value.Split('&')
.Select(x =>
{
var kvp = x.Split('=');
return new KeyValuePair<string, string>(kvp[0], kvp[1]);
})
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
return connectionString;
}
public IEnumerable<HostEndpointWithPort> GetBootstrapEndpoints()
{
var hosts = new List<HostEndpoint>(Hosts);
if (RandomizeSeedHosts)
{
hosts = hosts.Shuffle();
}
foreach (var endpoint in hosts)
{
if (endpoint.Port != null)
{
yield return new HostEndpointWithPort(endpoint.Host, endpoint.Port.GetValueOrDefault());
}
else
{
yield return new HostEndpointWithPort(endpoint.Host, Scheme == Scheme.Https ? HttpsPort: HttpPort);
}
}
}
internal Uri GetDnsBootStrapUri()
{
return new UriBuilder
{
Scheme = Scheme.ToString(),
Host = Hosts.First().Host,
Port = Hosts.First().Port ?? (Scheme == Scheme.Https ? HttpsPort : HttpPort)
}.Uri;
}
internal Uri GetAnalyticsServiceUri()
{
return new UriBuilder
{
Scheme = Scheme.ToString(),
Host = Hosts.First().Host,
Port = Hosts.First().Port ?? (Scheme == Scheme.Https ? HttpsPort : HttpPort),
Path = ExecuteQueryPath
}.Uri;
}
public bool TryGetParameter(string key, out object parameter)
{
if (Parameters.TryGetValue(key, out var value))
{
parameter = value;
return true;
}
parameter = string.Empty;
return false;
}
public bool TryGetParameter(string key, out string parameter)
{
if (Parameters.TryGetValue(key, out var value))
{
parameter = value;
return true;
}
parameter = string.Empty;
return false;
}
public bool TryGetParameter(string key, out int parameter)
{
if (TryGetParameter(key, out string value))
{
parameter = Convert.ToInt32(value);
return true;
}
parameter = default;
return false;
}
public bool TryGetParameter(string key, out uint parameter)
{
if (TryGetParameter(key, out string value))
{
parameter = Convert.ToUInt32(value);
return true;
}
parameter = default;
return false;
}
public bool TryGetParameter(string key, out float parameter)
{
if (TryGetParameter(key, out string value))
{
parameter = Convert.ToSingle(value);
return true;
}
parameter = default;
return false;
}
public bool TryGetParameter(string key, out TimeSpan parameter)
{
if (TryGetParameter(key, out string value))
{
parameter = TimeSpan.FromMilliseconds(Convert.ToUInt32(value));
return true;
}
parameter = default;
return false;
}
public bool TryGetParameter(string key, out bool parameter)
{
if (TryGetParameter(key, out string value))
{
if (value == "on")
{
parameter = true;
return true;
}
if (value == "off")
{
parameter = false;
return true;
}
parameter = Convert.ToBoolean(value);
return true;
}
parameter = default;
return false;
}
public override string ToString()
{
var builder = new StringBuilder();
builder.Append(Scheme switch
{
Scheme.Http => "http://",
Scheme.Https => "https://",
_ => throw new ArgumentException($"Unknown scheme {Scheme}")
});
if (!string.IsNullOrEmpty(Username))
{
builder.Append(Uri.EscapeDataString(Username));
builder.Append('@');
}
for (var hostIndex = 0; hostIndex < Hosts.Count; hostIndex++)
{
if (hostIndex > 0)
{
builder.Append(',');
}
builder.Append(Hosts[hostIndex].Host);
if (Hosts[hostIndex].Port != null)
{
builder.AppendFormat(":{0}", Hosts[hostIndex].Port);
}
}
if (Parameters.Count > 0)
{
var first = true;
foreach (var parameter in Parameters)
{
if (first)
{
first = false;
builder.Append('?');
}
else
{
builder.Append('&');
}
builder.Append(Uri.EscapeDataString(parameter.Key));
builder.Append('=');
builder.Append(Uri.EscapeDataString(parameter.Value));
}
}
return builder.ToString();
}
}
internal enum Scheme
{
/// <summary>
/// Non-TLS couchbase clusters.
/// </summary>
Http,
/// <summary>
/// For TLS/SSL clusters.
/// </summary>
Https
}