forked from elastic/elasticsearch-net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnionConverter.cs
237 lines (202 loc) · 6.45 KB
/
UnionConverter.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
// 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.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using Elastic.Clients.Elasticsearch.Aggregations;
namespace Elastic.Clients.Elasticsearch.Serialization;
internal sealed class UnionConverter : JsonConverterFactory
{
// Because converters registered on JsonSerializerOptions take priority over the JsonConverter attribute on the type, we need a way to
// mark those types we don't want to use the default union converter. This set is used for that purpose, until a better option can be
// found.
private static readonly HashSet<Type> TypesToSkip = new()
{
typeof(Core.Search.SourceConfig),
typeof(Script)
};
public override bool CanConvert(Type typeToConvert) => !TypesToSkip.Contains(typeToConvert) &&
(typeToConvert.Name == typeof(Union<,>).Name || (typeToConvert.BaseType is not null && typeToConvert.BaseType.Name == typeof(Union<,>).Name));
public override JsonConverter CreateConverter(
Type type,
JsonSerializerOptions options)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Buckets<>))
{
// TODO - Could potentially cache an instance for each bucket type and reuse it
var bucketType = type.GetGenericArguments()[0];
return (JsonConverter)Activator.CreateInstance(typeof(BucketsConverter<>).MakeGenericType(bucketType));
}
// Fallback to generalised converter
Type itemOneType, itemTwoType;
if (type.Name == typeof(Union<,>).Name)
{
itemOneType = type.GetGenericArguments()[0];
itemTwoType = type.GetGenericArguments()[1];
}
else
{
itemOneType = type.BaseType.GetGenericArguments()[0];
itemTwoType = type.BaseType.GetGenericArguments()[1];
}
JsonConverter converter;
if (type.Name == typeof(Union<,>).Name)
{
converter = (JsonConverter)Activator.CreateInstance(typeof(UnionConverterInner<,>).MakeGenericType(itemOneType, itemTwoType));
}
else
{
converter = (JsonConverter)Activator.CreateInstance(typeof(DerivedUnionConverterInner<,,>).MakeGenericType(type, itemOneType, itemTwoType));
}
return converter;
}
private class DerivedUnionConverterInner<TType, TItem1, TItem2> : JsonConverter<TType>
where TType : Union<TItem1, TItem2>
{
public override TType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// TODO - Aggregate Exception if both fail
var readerCopy = reader;
try
{
var itemOne = JsonSerializer.Deserialize<TItem1>(ref readerCopy, options);
if (itemOne is IUnionVerifiable verifiable)
{
if (verifiable.IsSuccessful)
{
reader = readerCopy;
return (TType)Activator.CreateInstance(typeof(TType), itemOne);
}
}
else if (itemOne is not null)
{
reader = readerCopy;
return (TType)Activator.CreateInstance(typeof(TType), itemOne);
}
}
catch
{
// TODO - Store for aggregate exception
}
//if (reader.TokenType == JsonTokenType.StartObject)
//{
// requiresEndObject = true;
// reader.Read();
//}
try
{
var itemTwo = JsonSerializer.Deserialize<TItem2>(ref reader, options);
if (itemTwo is not null)
{
return (TType)Activator.CreateInstance(typeof(TType), itemTwo);
}
}
catch
{
// TODO - Store for aggregate exception
}
throw new JsonException("Unable to deserialize union."); // TODO - Add inner aggregate exception.
}
public override void Write(Utf8JsonWriter writer, TType value,
JsonSerializerOptions options)
{
if (value.Item1 is not null)
{
JsonSerializer.Serialize(writer, value.Item1, value.Item1.GetType(), options);
return;
}
if (value.Item2 is not null)
{
JsonSerializer.Serialize(writer, value.Item2, value.Item2.GetType(), options);
return;
}
throw new JsonException("Invalid union type.");
}
}
private class UnionConverterInner<TItem1, TItem2> : JsonConverter<Union<TItem1, TItem2>>
{
public override Union<TItem1, TItem2>? Read(ref Utf8JsonReader reader, Type typeToConvert,
JsonSerializerOptions options)
{
var readerCopy = reader;
try
{
var itemOne = JsonSerializer.Deserialize<TItem1>(ref readerCopy, options);
if (itemOne is IUnionVerifiable verifiable)
{
if (verifiable.IsSuccessful)
{
reader = readerCopy;
return (TItem1)Activator.CreateInstance(typeof(TItem1), itemOne);
}
}
else if (itemOne is not null)
{
reader = readerCopy;
return (TItem1)Activator.CreateInstance(typeof(TItem1), itemOne);
}
}
catch
{
// TODO - Store for aggregate exception
}
try
{
var itemTwo = JsonSerializer.Deserialize<TItem2>(ref reader, options);
if (itemTwo is not null)
{
return (TItem2)Activator.CreateInstance(typeof(TItem2), itemTwo);
}
}
catch
{
// TODO - Store for aggregate exception
}
throw new JsonException("Unable to deserialize union."); // TODO - Add inner aggregate exception.
}
public override void Write(Utf8JsonWriter writer, Union<TItem1, TItem2> value,
JsonSerializerOptions options)
{
if (value.Item1 is not null)
{
JsonSerializer.Serialize(writer, value.Item1, value.Item1.GetType(), options);
return;
}
if (value.Item2 is not null)
{
JsonSerializer.Serialize(writer, value.Item2, value.Item2.GetType(), options);
return;
}
throw new JsonException("Invalid union type");
}
}
private class BucketsConverter<TBucket> : JsonConverter<Buckets<TBucket>>
{
public override Buckets<TBucket>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.TokenType switch
{
JsonTokenType.Null => null,
JsonTokenType.StartArray => new(JsonSerializer.Deserialize<IReadOnlyCollection<TBucket>>(ref reader, options)),
JsonTokenType.StartObject => new(JsonSerializer.Deserialize<IReadOnlyDictionary<string, TBucket>>(ref reader, options)),
_ => throw new JsonException("Invalid bucket type")
};
}
public override void Write(Utf8JsonWriter writer, Buckets<TBucket> value, JsonSerializerOptions options)
{
if (value.Item1 is { } item1)
{
JsonSerializer.Serialize(writer, item1, options);
return;
}
if (value.Item2 is { } item2)
{
JsonSerializer.Serialize(writer, item2, options);
return;
}
writer.WriteNullValue();
}
}
}