-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathExtensions.cs
314 lines (259 loc) · 9.35 KB
/
Extensions.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
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
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#if ELASTICSEARCH_SERVERLESS
namespace Elastic.Clients.Elasticsearch.Serverless;
#else
namespace Elastic.Clients.Elasticsearch;
#endif
internal static class Extensions
{
private static readonly ConcurrentDictionary<string, object> EnumCache = new();
//internal static bool NotWritable(this Query q) => q == null || !q.IsWritable;
//internal static bool NotWritable(this IEnumerable<Query> qs) => qs == null || qs.All(q => q.NotWritable());
internal static string ToEnumValue<T>(this T enumValue) where T : struct
{
var enumType = typeof(T);
var name = Enum.GetName(enumType, enumValue);
var enumMemberAttribute = enumType.GetField(name).GetCustomAttribute<EnumMemberAttribute>();
//if (enumMemberAttribute != null)
//return enumMemberAttribute.Value;
//var alternativeEnumMemberAttribute = enumType.GetField(name).GetCustomAttribute<AlternativeEnumMemberAttribute>();
return enumMemberAttribute != null
? enumMemberAttribute.Value
: enumValue.ToString();
}
internal static T? ToEnum<T>(this string str, StringComparison comparison = StringComparison.OrdinalIgnoreCase) where T : struct
{
if (str == null)
return null;
var enumType = typeof(T);
var key = $"{enumType.Name}.{str}";
if (EnumCache.TryGetValue(key, out var value))
return (T)value;
foreach (var name in Enum.GetNames(enumType))
{
if (name.Equals(str, comparison))
{
var v = (T)Enum.Parse(enumType, name, true);
EnumCache.TryAdd(key, v);
return v;
}
var enumFieldInfo = enumType.GetField(name);
var enumMemberAttribute = enumFieldInfo.GetCustomAttribute<EnumMemberAttribute>();
if (enumMemberAttribute?.Value.Equals(str, comparison) ?? false)
{
var v = (T)Enum.Parse(enumType, name);
EnumCache.TryAdd(key, v);
return v;
}
//var alternativeEnumMemberAttribute = enumFieldInfo.GetCustomAttribute<AlternativeEnumMemberAttribute>();
//if (alternativeEnumMemberAttribute?.Value.Equals(str, comparison) ?? false)
//{
// var v = (T)Enum.Parse(enumType, name);
// EnumCache.TryAdd(key, v);
// return v;
//}
}
return null;
}
internal static TReturn InvokeOrDefault<T, TReturn>(this Func<T, TReturn> func, T @default)
where T : class, TReturn where TReturn : class =>
func?.Invoke(@default) ?? @default;
internal static TReturn InvokeOrDefault<T1, T2, TReturn>(this Func<T1, T2, TReturn> func, T1 @default,
T2 param2)
where T1 : class, TReturn where TReturn : class =>
func?.Invoke(@default, param2) ?? @default;
internal static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property) =>
items.GroupBy(property).Select(x => x.First());
internal static string Utf8String(this byte[] bytes) =>
bytes == null ? null : Encoding.UTF8.GetString(bytes, 0, bytes.Length);
internal static byte[] Utf8Bytes(this string s) => s.IsNullOrEmpty() ? null : Encoding.UTF8.GetBytes(s);
internal static bool IsNullOrEmpty(this IndexName value) => value == null || value.GetHashCode() == 0;
internal static bool IsNullable(this Type type) =>
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
internal static void ThrowIfNullOrEmpty(this string @object, string parameterName, string when = null)
{
@object.ThrowIfNull(parameterName, when);
if (string.IsNullOrWhiteSpace(@object))
{
throw new ArgumentException(
"Argument can't be null or empty" + (when.IsNullOrEmpty() ? "" : " when " + when), parameterName);
}
}
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Global
internal static void ThrowIfEmpty<T>(this IEnumerable<T> @object, string parameterName)
{
if (@object == null)
throw new ArgumentNullException(parameterName);
if ([email protected]())
throw new ArgumentException("Argument can not be an empty collection", parameterName);
}
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Global
internal static T[] NotEmpty<T>(this IEnumerable<T> @object, string parameterName)
{
if ([email protected](out var enumerated))
throw new ArgumentException("Argument can not be an empty collection", parameterName);
return enumerated;
}
internal static bool HasAny<T>(this IEnumerable<T> list, out T[] enumerated)
{
enumerated = list == null ? null : list as T[] ?? list.ToArray();
return enumerated.HasAny();
}
internal static List<T> AsInstanceOrToListOrDefault<T>(this IEnumerable<T> list) =>
list as List<T> ?? list?.ToList() ?? new List<T>();
internal static List<T> AsInstanceOrToListOrNull<T>(this IEnumerable<T> list) =>
list as List<T> ?? list?.ToList();
internal static List<T> EagerConcat<T>(this IEnumerable<T> list, IEnumerable<T> other)
{
var first = list.AsInstanceOrToListOrDefault();
if (other == null)
return first;
var second = other.AsInstanceOrToListOrDefault();
var newList = new List<T>(first.Count + second.Count);
newList.AddRange(first);
newList.AddRange(second);
return newList;
}
internal static IEnumerable<T> AddIfNotNull<T>(this IEnumerable<T> list, T other)
{
if (other == null)
return list;
var l = list.AsInstanceOrToListOrDefault();
l.Add(other);
return l;
}
internal static bool HasAny<T>(this IEnumerable<T> list, Func<T, bool> predicate) =>
list != null && list.Any(predicate);
internal static bool HasAny<T>(this IEnumerable<T> list) => list != null && list.Any();
internal static bool IsNullOrEmpty<T>(this IEnumerable<T>? list)
{
if (list is null)
return true;
var enumerable = list as T[] ?? list.ToArray();
return (enumerable.Length == 0) || enumerable.All(x => x is null);
}
internal static void ThrowIfNull<T>(this T value, string name, string message = null)
{
if (value == null && message.IsNullOrEmpty())
throw new ArgumentNullException(name);
else if (value == null)
throw new ArgumentNullException(name, "Argument can not be null when " + message);
}
internal static bool IsNullOrEmpty(this string? value) => string.IsNullOrWhiteSpace(value);
internal static bool IsNullOrEmptyCommaSeparatedList(this string? value, [NotNullWhen(false)] out string[]? split)
{
split = null;
if (string.IsNullOrWhiteSpace(value))
return true;
split = value.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Where(t => !t.IsNullOrEmpty())
.Select(t => t.Trim())
.ToArray();
return split.Length == 0;
}
internal static List<T> ToListOrNullIfEmpty<T>(this IEnumerable<T> enumerable)
{
var list = enumerable.AsInstanceOrToListOrNull();
return list != null && list.Count > 0 ? list : null;
}
internal static void AddIfNotNull<T>(this IList<T> list, T item) where T : class
{
if (item == null)
return;
list.Add(item);
}
internal static void AddRangeIfNotNull<T>(this List<T> list, IEnumerable<T> item) where T : class
{
if (item == null)
return;
list.AddRange(item.Where(x => x != null));
}
internal static Dictionary<TKey, TValue> NullIfNoKeys<TKey, TValue>(this Dictionary<TKey, TValue> dictionary)
{
var i = dictionary?.Count;
return i.GetValueOrDefault(0) > 0 ? dictionary : null;
}
internal static async Task ForEachAsync<TSource, TResult>(
this IEnumerable<TSource> lazyList,
Func<TSource, long, Task<TResult>> taskSelector,
Action<TSource, TResult> resultProcessor,
Action<Exception> done,
int maxDegreeOfParallelism,
SemaphoreSlim additionalRateLimiter = null
)
{
var semaphore = new SemaphoreSlim(maxDegreeOfParallelism, maxDegreeOfParallelism);
long page = 0;
try
{
var tasks = new List<Task>(maxDegreeOfParallelism);
foreach (var item in lazyList)
{
tasks.Add(ProcessAsync(item, taskSelector, resultProcessor, semaphore, additionalRateLimiter,
page++));
if (tasks.Count < maxDegreeOfParallelism)
continue;
var task = await Task.WhenAny(tasks).ConfigureAwait(false);
if (task.Exception != null && task.IsFaulted && task.Exception.Flatten().InnerExceptions.First() is
{ } e)
{
ExceptionDispatchInfo.Capture(e).Throw();
return;
}
tasks.Remove(task);
}
await Task.WhenAll(tasks).ConfigureAwait(false);
done(null);
}
catch (Exception e)
{
done(e);
throw;
}
}
private static async Task ProcessAsync<TSource, TResult>(
TSource item,
Func<TSource, long, Task<TResult>> taskSelector,
Action<TSource, TResult> resultProcessor,
SemaphoreSlim localRateLimiter,
SemaphoreSlim additionalRateLimiter,
long page
)
{
if (localRateLimiter != null)
await localRateLimiter.WaitAsync().ConfigureAwait(false);
if (additionalRateLimiter != null)
await additionalRateLimiter.WaitAsync().ConfigureAwait(false);
try
{
var result = await taskSelector(item, page).ConfigureAwait(false);
resultProcessor(item, result);
}
finally
{
localRateLimiter?.Release();
additionalRateLimiter?.Release();
}
}
internal static bool NullOrEquals<T>(this T o, T other)
{
if (o == null && other == null)
return true;
if (o == null || other == null)
return false;
return o.Equals(other);
}
}