Skip to content

Commit c202125

Browse files
committed
Switch to custom SafeSkip() method that works with partial JSON blocks (#8720)
(cherry picked from commit e3d86ff)
1 parent 59f8977 commit c202125

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

src/Elastic.Clients.Elasticsearch/_Shared/Next/JsonReaderExtensions.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,29 @@ public static JsonException UnexpectedTokenException(this ref Utf8JsonReader rea
6363
return new JsonException($"Expected JSON {valid} token, but got '{reader.TokenType}'.");
6464
}
6565

66+
public static void SafeSkip(this ref Utf8JsonReader reader)
67+
{
68+
// Utf8JsonReader.Skip() unconditionally throws, if the reader instance is constructed with `isFinalBlock = false`.
69+
// This may happen when reading from streams or pipes.
70+
71+
// For custom converters, System.Text.JSON always guarantees that the entire JSON value for the current scope is available.
72+
// See:
73+
// https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to#steps-to-follow-the-basic-pattern
74+
75+
// > Override the Read method to deserialize the incoming JSON and convert it to type T. Use the Utf8JsonReader that's passed to
76+
// > the method to read the JSON. You don't have to worry about handling partial data, as the serializer passes all the data for
77+
// > the current JSON scope.
78+
79+
// We use `TrySkip()` here to avoid the exception.
80+
81+
if (!reader.TrySkip())
82+
{
83+
throw new InvalidOperationException(
84+
"Failed to skip JSON token. This case should never happen and indicates a severe problem. " +
85+
"Please open an issue in the Github repository.");
86+
}
87+
}
88+
6689
/// <summary>
6790
/// Compares the JSON encoded text to the JSON token value in the source and returns <see langword="true"/> if they match.
6891
/// </summary>

src/Elastic.Clients.Elasticsearch/_Shared/Next/JsonUnionSelector.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ public static UnionTag MatchProperty(ref Utf8JsonReader reader, JsonSerializerOp
119119
}
120120

121121
internalReader.Read();
122-
internalReader.Skip();
122+
internalReader.SafeSkip();
123123
}
124124

125125
return UnionTag.None;

src/Elastic.Clients.Elasticsearch/_Shared/Types/Core/Bulk/BulkResponseItemConverter.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ public override ResponseItem Read(ref Utf8JsonReader reader, Type typeToConvert,
108108

109109
if (options.UnmappedMemberHandling is JsonUnmappedMemberHandling.Skip)
110110
{
111-
reader.Skip();
111+
reader.SafeSkip();
112112
continue;
113113
}
114114

0 commit comments

Comments
 (0)