Skip to content

Add (experimental) native AOT support #8530

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<PackageId>Elastic.Clients.Elasticsearch</PackageId>
<Title>Elastic.Clients.Elasticsearch - Official Elasticsearch .NET Client</Title>
Expand All @@ -9,6 +10,7 @@
<ProduceReferenceAssembly>true</ProduceReferenceAssembly>
<PackageReadmeFile>README.md</PackageReadmeFile>
</PropertyGroup>

<PropertyGroup>
<IsPackable>true</IsPackable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
Expand All @@ -18,24 +20,38 @@
<Nullable>annotations</Nullable>
<PolySharpIncludeRuntimeSupportedAttributes>true</PolySharpIncludeRuntimeSupportedAttributes>
</PropertyGroup>

<PropertyGroup Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0')) or
$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net9.0'))">
<IsAotCompatible>true</IsAotCompatible>
</PropertyGroup>

<PropertyGroup>
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Elastic.Transport" Version="0.5.9" />
<PackageReference Include="Elastic.Transport" Version="0.8.0" />
<PackageReference Include="PolySharp" Version="1.15.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Tests" Key="$(ExposedPublicKey)" />
<InternalsVisibleTo Include="Tests.Domain" Key="$(ExposedPublicKey)" />
<InternalsVisibleTo Include="Benchmarks" Key="$(ExposedPublicKey)" />
</ItemGroup>

<ItemGroup>
<AssemblyAttribute Include="CLSCompliantAttribute">
<_Parameter1>true</_Parameter1>
</AssemblyAttribute>
</ItemGroup>

<ItemGroup>
<None Include="..\..\README.md" Pack="true" PackagePath="\" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ protected override (string ResolvedUrl, string UrlTemplate, Dictionary<string, s
[JsonConverter(typeof(SearchRequestOfTConverterFactory))]
public partial class SearchRequest<TInferDocument> : SearchRequest
{
static SearchRequest()
{
DynamicallyAccessed.PublicConstructors(typeof(SearchRequestOfTConverter<TInferDocument>));
Copy link
Member Author

@flobernd flobernd May 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might have to generate this for all generic types that are using converter factories to make Activator.CreateInstance succeed even when T is a value type (e.g. if the user for some reason uses struct for top level documents).

}

public SearchRequest(Indices? indices) : base(indices)
{
}
Expand Down Expand Up @@ -67,7 +72,9 @@ public override bool CanConvert(Type typeToConvert) =>
{
var args = typeToConvert.GetGenericArguments();

#pragma warning disable IL3050
return (JsonConverter)Activator.CreateInstance(typeof(SearchRequestOfTConverter<>).MakeGenericType(args[0]));
#pragma warning restore IL3050
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ private static IEnumerable<T> EsqlToObject<T>(ElasticsearchClient client, EsqlQu
{
// TODO: Improve performance

// TODO: fixme
#pragma warning disable IL2026, IL3050
using var doc = JsonSerializer.Deserialize<JsonDocument>(response.Data) ?? throw new JsonException();
#pragma warning restore IL2026, IL3050

if (!doc.RootElement.TryGetProperty("columns"u8, out var columns) || (columns.ValueKind is not JsonValueKind.Array))
throw new JsonException("");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ internal DateMath(Union<DateTime, string> anchor, DateMathTime range, DateMathOp

public static implicit operator DateMath(string dateMath) => FromString(dateMath);

public static DateMath FromString(string dateMath)
public static DateMath FromString(string? dateMath)
{
if (dateMath == null)
return null;
if (dateMath is null)
throw new ArgumentNullException(nameof(dateMath));

var match = DateMathRegex.Match(dateMath);
if (!match.Success)
Expand All @@ -61,9 +61,12 @@ public static DateMath FromString(string dateMath)
var rangeString = match.Groups["ranges"].Value;
do
{
var nextRangeStart = rangeString.Substring(1).IndexOfAny(new[] { '+', '-', '/' });
var nextRangeStart = rangeString[1..].IndexOfAny(['+', '-', '/']);
if (nextRangeStart == -1)
{
nextRangeStart = rangeString.Length - 1;
}

var unit = rangeString.Substring(1, nextRangeStart);
if (rangeString.StartsWith("+", StringComparison.Ordinal))
{
Expand All @@ -73,19 +76,25 @@ public static DateMath FromString(string dateMath)
else if (rangeString.StartsWith("-", StringComparison.Ordinal))
{
math = math.Subtract(unit);
rangeString = rangeString.Substring(nextRangeStart + 1);
rangeString = rangeString[(nextRangeStart + 1)..];
}
else
rangeString = null;
{
break;
}
} while (!rangeString.IsNullOrEmpty());
}

if (match.Groups["rounding"].Success)
if (!match.Groups["rounding"].Success)
{
var rounding = match.Groups["rounding"].Value.Substring(1).ToEnum<DateMathTimeUnit>(StringComparison.Ordinal);
if (rounding.HasValue)
return math.RoundTo(rounding.Value);
return math;
}

if (EnumValue<DateMathTimeUnit>.TryParse(match.Groups["rounding"].Value[1..], out var rounding))
{
return math.RoundTo(rounding);
}

return math;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,9 @@ public DateMathTime(string timeUnit, MidpointRounding rounding = MidpointRoundin
{
"M" => DateMathTimeUnit.Month,
"m" => DateMathTimeUnit.Minute,
_ => intervalValue.ToEnum<DateMathTimeUnit>().GetValueOrDefault(),
_ => EnumValue<DateMathTimeUnit>.TryParse(intervalValue, out var result) ? result : default
};

SetWholeFactorIntervalAndSeconds(fraction, interval, rounding);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
// 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.Diagnostics.CodeAnalysis;

#if !NET5_0_OR_GREATER

using System.Linq;

#endif

namespace Elastic.Clients.Elasticsearch;
Expand All @@ -12,12 +16,13 @@ namespace Elastic.Clients.Elasticsearch;
using System.Collections.Generic;
using System.Runtime.Serialization;

internal static class EnumValueParser<T>
internal static class EnumValue<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T>
where T : struct, Enum
{
private static readonly Dictionary<string, T> ValueMap = new(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<T, string> NameMap = new();

static EnumValueParser()
static EnumValue()
{
#if NET5_0_OR_GREATER
foreach (var value in Enum.GetValues<T>())
Expand All @@ -27,12 +32,14 @@ static EnumValueParser()
{
var name = value.ToString();
ValueMap[name] = value;
NameMap[value] = name;

var field = typeof(T).GetField(name);
var attribute = (EnumMemberAttribute?)Attribute.GetCustomAttribute(field!, typeof(EnumMemberAttribute));
if (attribute?.Value is not null)
{
ValueMap[attribute.Value] = value;
NameMap[value] = attribute.Value;
}
}
}
Expand All @@ -51,4 +58,19 @@ public static T Parse(string input)

throw new ArgumentException($"Unknown member '{input}' for enum '{typeof(T).Name}'.");
}

public static bool TryGetString(T value, [NotNullWhen(true)] out string? result)
{
return NameMap.TryGetValue(value, out result);
}

public static string GetString(T value)
{
if (NameMap.TryGetValue(value, out var result))
{
return result;
}

throw new ArgumentException($"Unknown member '{value}' for enum '{typeof(T).Name}'.");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,115 +3,17 @@
// 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;

namespace Elastic.Clients.Elasticsearch;

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)
{
Expand Down Expand Up @@ -164,9 +66,6 @@ internal static IEnumerable<T> AddIfNotNull<T>(this IEnumerable<T> list, T 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)
Expand Down Expand Up @@ -195,7 +94,7 @@ internal static bool IsNullOrEmptyCommaSeparatedList(this string? value, [NotNul
if (string.IsNullOrWhiteSpace(value))
return true;

split = value.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
split = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Where(t => !t.IsNullOrEmpty())
.Select(t => t.Trim())
.ToArray();
Expand Down Expand Up @@ -224,12 +123,6 @@ internal static void AddRangeIfNotNull<T>(this List<T> list, IEnumerable<T> item
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,
Expand Down Expand Up @@ -297,14 +190,4 @@ long page
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);
}
}
Loading
Loading