Skip to content
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

Ensure JsonTypeInfo does not fail configuration for valid metadata originating from fast-path sourcegen #72630

Merged
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
Expand Up @@ -61,7 +61,7 @@ public JsonMetadataServicesConverter(JsonConverter<T> converter)
}

internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, out T? value)
=> Converter.OnTryRead(ref reader, typeToConvert, options, ref state, out value);
=> Converter.OnTryRead(ref reader, typeToConvert, options, ref state, out value);

internal override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state)
{
Expand All @@ -70,15 +70,17 @@ internal override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializer
Debug.Assert(options == jsonTypeInfo.Options);

if (!state.SupportContinuation &&
jsonTypeInfo.HasSerializeHandler &&
krwq marked this conversation as resolved.
Show resolved Hide resolved
jsonTypeInfo is JsonTypeInfo<T> info &&
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
info.SerializeHandler != null &&
!state.CurrentContainsMetadata && // Do not use the fast path if state needs to write metadata.
info.Options.SerializerContext?.CanUseSerializationLogic == true)
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
{
Debug.Assert(info.SerializeHandler != null);
info.SerializeHandler(writer, value);
return true;
}

jsonTypeInfo.ValidateCanBeUsedForMetadataSerialization();
return Converter.OnTryWrite(writer, value, options, ref state);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ private void BeginRead(ref ReadStack state, ref Utf8JsonReader reader, JsonSeria
{
JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo;

jsonTypeInfo.ValidateCanBeUsedForDeserialization();
jsonTypeInfo.ValidateCanBeUsedForMetadataSerialization();

if (jsonTypeInfo.ParameterCount != jsonTypeInfo.ParameterCache!.Count)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ private static void WriteUsingGeneratedSerializer<TValue>(Utf8JsonWriter writer,
{
Debug.Assert(writer != null);

if (jsonTypeInfo.HasSerialize &&
if (jsonTypeInfo.HasSerializeHandler &&
jsonTypeInfo is JsonTypeInfo<TValue> typedInfo &&
typedInfo.Options.SerializerContext?.CanUseSerializationLogic == true)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ internal JsonPropertyInfo GetProperty(
{
PropertyRef propertyRef;

ValidateCanBeUsedForDeserialization();
ValidateCanBeUsedForMetadataSerialization();
ulong key = GetKey(propertyName);

// Keep a local copy of the cache in case it changes by another thread.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,16 +267,16 @@ public JsonPolymorphismOptions? PolymorphismOptions
private JsonTypeInfo? _elementTypeInfo;

// Avoids having to perform an expensive cast to JsonTypeInfo<T> to check if there is a Serialize method.
internal bool HasSerialize { get; private protected set; }
internal bool HasSerializeHandler { get; private protected set; }

// Configure would normally have thrown why initializing properties for source gen but type had SerializeHandler
// so it is allowed to be used for serialization but it will throw if used for deserialization
internal bool ThrowOnDeserialize { get; private protected set; }
// so it is allowed to be used for fast-path serialization but it will throw if used for metadata-based serialization
internal bool MetadataSerializationNotSupported { get; private protected set; }

[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void ValidateCanBeUsedForDeserialization()
internal void ValidateCanBeUsedForMetadataSerialization()
{
if (ThrowOnDeserialize)
if (MetadataSerializationNotSupported)
{
ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeProperties(Options.TypeInfoResolver, Type);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ private protected set
{
Debug.Assert(!IsConfigured, "We should not mutate configured JsonTypeInfo");
_serialize = value;
HasSerialize = value != null;
HasSerializeHandler = value != null;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,13 @@ internal override JsonParameterInfoValues[] GetParameterInfoValues()
JsonParameterInfoValues[] array;
if (CtorParamInitFunc == null || (array = CtorParamInitFunc()) == null)
{
ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeCtorParams(Options.TypeInfoResolver, Type);
return null!;
if (SerializeHandler == null)
{
ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeCtorParams(Options.TypeInfoResolver, Type);
}
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved

array = Array.Empty<JsonParameterInfoValues>();
MetadataSerializationNotSupported = true;
}

return array;
Expand Down Expand Up @@ -139,13 +144,12 @@ internal override void LateAddProperties()
return;
}

if (SerializeHandler != null && context?.CanUseSerializationLogic == true)
if (SerializeHandler == null)
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
{
ThrowOnDeserialize = true;
return;
ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeProperties(Options.TypeInfoResolver, Type);
}

ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeProperties(Options.TypeInfoResolver, Type);
MetadataSerializationNotSupported = true;
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,60 @@ public static void CombiningContexts_ResolveJsonTypeInfo_DifferentCasing()
Assert.Equal("lastName", personInfo.Properties[1].Name);
}

[Fact]
public static void FastPathSerialization_ResolvingJsonTypeInfo()
{
JsonSerializerOptions options = FastPathSerializationContext.Default.Options;

JsonTypeInfo<JsonMessage> jsonMessageInfo = (JsonTypeInfo<JsonMessage>)options.GetTypeInfo(typeof(JsonMessage));
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
Assert.NotNull(jsonMessageInfo.SerializeHandler);

var value = new JsonMessage { Message = "Hi" };
string expectedJson = """{"Message":"Hi","Length":2}""";

Assert.Equal(expectedJson, JsonSerializer.Serialize(value, jsonMessageInfo));
Assert.Equal(expectedJson, JsonSerializer.Serialize(value, options));

// Throws since deserialization without metadata is not supported
Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<JsonMessage>(expectedJson, jsonMessageInfo));
Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<JsonMessage>(expectedJson, options));
}

[Fact]
public static void FastPathSerialization_CombinedContext_ThrowsInvalidOperationException()
{
// TODO change exception assertions once https://github.com/dotnet/runtime/issues/71933 is fixed.

var options = new JsonSerializerOptions
{
TypeInfoResolver = JsonTypeInfoResolver.Combine(FastPathSerializationContext.Default, new DefaultJsonTypeInfoResolver())
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
};

JsonTypeInfo<JsonMessage> jsonMessageInfo = (JsonTypeInfo<JsonMessage>)options.GetTypeInfo(typeof(JsonMessage));
Assert.NotNull(jsonMessageInfo.SerializeHandler);

var value = new JsonMessage { Message = "Hi" };
Assert.Throws<InvalidOperationException>(() => JsonSerializer.Serialize(value, jsonMessageInfo));
Assert.Throws<InvalidOperationException>(() => JsonSerializer.Serialize(value, options));

JsonTypeInfo<ClassWithJsonMessage> classInfo = (JsonTypeInfo<ClassWithJsonMessage>)options.GetTypeInfo(typeof(ClassWithJsonMessage));
Assert.Null(classInfo.SerializeHandler);

var largerValue = new ClassWithJsonMessage { Message = value };
Assert.Throws<InvalidOperationException>(() => JsonSerializer.Serialize(largerValue, classInfo));
Assert.Throws<InvalidOperationException>(() => JsonSerializer.Serialize(largerValue, options));
}

[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Serialization)]
[JsonSerializable(typeof(JsonMessage))]
public partial class FastPathSerializationContext : JsonSerializerContext
{ }

public class ClassWithJsonMessage
{
public JsonMessage Message { get; set; }
}

[Theory]
[MemberData(nameof(GetCombiningContextsData))]
public static void CombiningContexts_Serialization<T>(T value, string expectedJson)
Expand Down