| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.IO; |
| | | 6 | | using System.IO.Pipelines; |
| | | 7 | | using System.Text.Json.Serialization.Converters; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | |
| | | 11 | | namespace System.Text.Json.Serialization.Metadata |
| | | 12 | | { |
| | | 13 | | public partial class JsonTypeInfo<T> |
| | | 14 | | { |
| | | 15 | | // This section provides helper methods guiding root-level serialization |
| | | 16 | | // of values corresponding according to the current JsonTypeInfo configuration. |
| | | 17 | | |
| | | 18 | | // Root serialization method for sync, non-streaming serialization |
| | | 19 | | internal void Serialize( |
| | | 20 | | Utf8JsonWriter writer, |
| | | 21 | | in T? rootValue, |
| | | 22 | | object? rootValueBoxed = null) |
| | 0 | 23 | | { |
| | 0 | 24 | | Debug.Assert(IsConfigured); |
| | 0 | 25 | | Debug.Assert(rootValueBoxed is null || rootValueBoxed is T); |
| | | 26 | | |
| | 0 | 27 | | if (CanUseSerializeHandler) |
| | 0 | 28 | | { |
| | | 29 | | // Short-circuit calls into SerializeHandler, if supported. |
| | | 30 | | // Even though this is already handled by JsonMetadataServicesConverter, |
| | | 31 | | // this avoids creating a WriteStack and calling into the converter infrastructure. |
| | | 32 | | |
| | 0 | 33 | | Debug.Assert(SerializeHandler != null); |
| | 0 | 34 | | Debug.Assert(Converter is JsonMetadataServicesConverter<T>); |
| | | 35 | | |
| | 0 | 36 | | SerializeHandler(writer, rootValue!); |
| | 0 | 37 | | writer.Flush(); |
| | 0 | 38 | | } |
| | 0 | 39 | | else if ( |
| | 0 | 40 | | #if NET |
| | 0 | 41 | | !typeof(T).IsValueType && |
| | 0 | 42 | | #endif |
| | 0 | 43 | | Converter.CanBePolymorphic && |
| | 0 | 44 | | rootValue is not null && |
| | 0 | 45 | | Options.TryGetPolymorphicTypeInfoForRootType(rootValue, out JsonTypeInfo? derivedTypeInfo)) |
| | 0 | 46 | | { |
| | 0 | 47 | | Debug.Assert(typeof(T) == typeof(object)); |
| | 0 | 48 | | derivedTypeInfo.SerializeAsObject(writer, rootValue); |
| | | 49 | | // NB flushing is handled by the derived type's serialization method. |
| | 0 | 50 | | } |
| | | 51 | | else |
| | 0 | 52 | | { |
| | 0 | 53 | | WriteStack state = default; |
| | 0 | 54 | | state.Initialize(this, rootValueBoxed); |
| | | 55 | | |
| | 0 | 56 | | bool success = EffectiveConverter.WriteCore(writer, rootValue, Options, ref state); |
| | 0 | 57 | | Debug.Assert(success); |
| | 0 | 58 | | writer.Flush(); |
| | 0 | 59 | | } |
| | 0 | 60 | | } |
| | | 61 | | |
| | | 62 | | internal Task SerializeAsync(Stream utf8Json, |
| | | 63 | | T? rootValue, |
| | | 64 | | CancellationToken cancellationToken, |
| | | 65 | | object? rootValueBoxed = null) |
| | 0 | 66 | | { |
| | 0 | 67 | | PooledByteBufferWriter writer = new PooledByteBufferWriter(Options.DefaultBufferSize, utf8Json); |
| | | 68 | | // Value chosen as 90% of the default buffer used in PooledByteBufferWriter. |
| | | 69 | | // This is a tradeoff between likelihood of needing to grow the array vs. utilizing most of the buffer |
| | 0 | 70 | | int flushThreshold = (int)(writer.Capacity * JsonSerializer.FlushThreshold); |
| | 0 | 71 | | return SerializeAsync(writer, rootValue, flushThreshold, cancellationToken, rootValueBoxed); |
| | 0 | 72 | | } |
| | | 73 | | |
| | | 74 | | internal Task SerializeAsync(PipeWriter utf8Json, |
| | | 75 | | T? rootValue, |
| | | 76 | | CancellationToken cancellationToken, |
| | | 77 | | object? rootValueBoxed = null) |
| | 0 | 78 | | { |
| | | 79 | | // Value chosen as 90% of 4 buffer segments in Pipes. This is semi-arbitrarily chosen and may be changed in |
| | 0 | 80 | | int flushThreshold = (int)(4 * PipeOptions.Default.MinimumSegmentSize * JsonSerializer.FlushThreshold); |
| | 0 | 81 | | return SerializeAsync(utf8Json, rootValue, flushThreshold, cancellationToken, rootValueBoxed); |
| | 0 | 82 | | } |
| | | 83 | | |
| | | 84 | | // Root serialization method for async streaming serialization. |
| | | 85 | | private async Task SerializeAsync( |
| | | 86 | | PipeWriter pipeWriter, |
| | | 87 | | T? rootValue, |
| | | 88 | | int flushThreshold, |
| | | 89 | | CancellationToken cancellationToken, |
| | | 90 | | object? rootValueBoxed = null) |
| | 0 | 91 | | { |
| | 0 | 92 | | Debug.Assert(IsConfigured); |
| | 0 | 93 | | Debug.Assert(rootValueBoxed is null || rootValueBoxed is T); |
| | | 94 | | |
| | 0 | 95 | | if (CanUseSerializeHandlerInStreaming) |
| | 0 | 96 | | { |
| | | 97 | | // Short-circuit calls into SerializeHandler, if the `CanUseSerializeHandlerInStreaming` heuristic allow |
| | | 98 | | |
| | 0 | 99 | | Debug.Assert(SerializeHandler != null); |
| | 0 | 100 | | Debug.Assert(CanUseSerializeHandler); |
| | 0 | 101 | | Debug.Assert(Converter is JsonMetadataServicesConverter<T>); |
| | | 102 | | |
| | 0 | 103 | | Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriter(Options, pipeWriter); |
| | | 104 | | |
| | | 105 | | try |
| | 0 | 106 | | { |
| | | 107 | | try |
| | 0 | 108 | | { |
| | 0 | 109 | | SerializeHandler(writer, rootValue!); |
| | 0 | 110 | | writer.Flush(); |
| | 0 | 111 | | } |
| | | 112 | | finally |
| | 0 | 113 | | { |
| | | 114 | | // Record the serialization size in both successful and failed operations, |
| | | 115 | | // since we want to immediately opt out of the fast path if it exceeds the threshold. |
| | 0 | 116 | | OnRootLevelAsyncSerializationCompleted(writer.BytesCommitted + writer.BytesPending); |
| | | 117 | | |
| | 0 | 118 | | Utf8JsonWriterCache.ReturnWriter(writer); |
| | 0 | 119 | | } |
| | | 120 | | |
| | 0 | 121 | | FlushResult result = await pipeWriter.FlushAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 122 | | if (result.IsCanceled) |
| | 0 | 123 | | { |
| | 0 | 124 | | ThrowHelper.ThrowOperationCanceledException_PipeWriteCanceled(); |
| | 0 | 125 | | } |
| | 0 | 126 | | } |
| | | 127 | | finally |
| | 0 | 128 | | { |
| | 0 | 129 | | if (pipeWriter is PooledByteBufferWriter disposable) |
| | 0 | 130 | | { |
| | 0 | 131 | | disposable.Dispose(); |
| | 0 | 132 | | } |
| | 0 | 133 | | } |
| | 0 | 134 | | } |
| | 0 | 135 | | else if ( |
| | 0 | 136 | | #if NET |
| | 0 | 137 | | !typeof(T).IsValueType && |
| | 0 | 138 | | #endif |
| | 0 | 139 | | Converter.CanBePolymorphic && |
| | 0 | 140 | | rootValue is not null && |
| | 0 | 141 | | Options.TryGetPolymorphicTypeInfoForRootType(rootValue, out JsonTypeInfo? derivedTypeInfo)) |
| | 0 | 142 | | { |
| | 0 | 143 | | Debug.Assert(typeof(T) == typeof(object)); |
| | 0 | 144 | | await derivedTypeInfo.SerializeAsObjectAsync(pipeWriter, rootValue, flushThreshold, cancellationToken).C |
| | 0 | 145 | | } |
| | | 146 | | else |
| | 0 | 147 | | { |
| | | 148 | | bool isFinalBlock; |
| | 0 | 149 | | WriteStack state = default; |
| | 0 | 150 | | state.Initialize(this, |
| | 0 | 151 | | rootValueBoxed, |
| | 0 | 152 | | supportContinuation: true, |
| | 0 | 153 | | supportAsync: true); |
| | | 154 | | |
| | 0 | 155 | | if (!pipeWriter.CanGetUnflushedBytes) |
| | 0 | 156 | | { |
| | 0 | 157 | | ThrowHelper.ThrowInvalidOperationException_PipeWriterDoesNotImplementUnflushedBytes(pipeWriter); |
| | 0 | 158 | | } |
| | 0 | 159 | | state.PipeWriter = pipeWriter; |
| | 0 | 160 | | state.CancellationToken = cancellationToken; |
| | | 161 | | |
| | 0 | 162 | | var writer = new Utf8JsonWriter(pipeWriter, Options.GetWriterOptions()); |
| | | 163 | | |
| | | 164 | | try |
| | 0 | 165 | | { |
| | 0 | 166 | | state.FlushThreshold = flushThreshold; |
| | | 167 | | |
| | | 168 | | do |
| | 0 | 169 | | { |
| | | 170 | | try |
| | 0 | 171 | | { |
| | 0 | 172 | | isFinalBlock = EffectiveConverter.WriteCore(writer, rootValue, Options, ref state); |
| | | 173 | | |
| | 0 | 174 | | if (state.SuppressFlush) |
| | 0 | 175 | | { |
| | 0 | 176 | | Debug.Assert(!isFinalBlock); |
| | 0 | 177 | | Debug.Assert(state.PendingTask is not null); |
| | 0 | 178 | | state.SuppressFlush = false; |
| | 0 | 179 | | } |
| | | 180 | | else |
| | 0 | 181 | | { |
| | 0 | 182 | | writer.Flush(); |
| | 0 | 183 | | FlushResult result = await pipeWriter.FlushAsync(cancellationToken).ConfigureAwait(false |
| | 0 | 184 | | if (result.IsCanceled || result.IsCompleted) |
| | 0 | 185 | | { |
| | 0 | 186 | | if (result.IsCanceled) |
| | 0 | 187 | | { |
| | 0 | 188 | | ThrowHelper.ThrowOperationCanceledException_PipeWriteCanceled(); |
| | 0 | 189 | | } |
| | | 190 | | |
| | | 191 | | // Pipe is completed, no one is reading so no point in continuing serialization |
| | 0 | 192 | | return; |
| | | 193 | | } |
| | 0 | 194 | | } |
| | 0 | 195 | | } |
| | | 196 | | finally |
| | 0 | 197 | | { |
| | | 198 | | // Await any pending resumable converter tasks (currently these can only be IAsyncEnumerator |
| | | 199 | | // Note that pending tasks are always awaited, even if an exception has been thrown or the c |
| | 0 | 200 | | if (state.PendingTask is not null) |
| | 0 | 201 | | { |
| | | 202 | | // Exceptions should only be propagated by the resuming converter |
| | | 203 | | #if NET |
| | 0 | 204 | | await state.PendingTask.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing); |
| | | 205 | | #else |
| | | 206 | | try |
| | | 207 | | { |
| | | 208 | | await state.PendingTask.ConfigureAwait(false); |
| | | 209 | | } |
| | | 210 | | catch { } |
| | | 211 | | #endif |
| | 0 | 212 | | } |
| | | 213 | | |
| | | 214 | | // Dispose any pending async disposables (currently these can only be completed IAsyncEnumer |
| | 0 | 215 | | if (state.CompletedAsyncDisposables?.Count > 0) |
| | 0 | 216 | | { |
| | 0 | 217 | | await state.DisposeCompletedAsyncDisposables().ConfigureAwait(false); |
| | 0 | 218 | | } |
| | 0 | 219 | | } |
| | | 220 | | |
| | 0 | 221 | | } while (!isFinalBlock); |
| | | 222 | | |
| | 0 | 223 | | if (CanUseSerializeHandler) |
| | 0 | 224 | | { |
| | | 225 | | // On successful serialization, record the serialization size |
| | | 226 | | // to determine potential suitability of the type for |
| | | 227 | | // fast-path serialization in streaming methods. |
| | 0 | 228 | | Debug.Assert(writer.BytesPending == 0); |
| | 0 | 229 | | OnRootLevelAsyncSerializationCompleted(writer.BytesCommitted); |
| | 0 | 230 | | } |
| | 0 | 231 | | } |
| | 0 | 232 | | catch |
| | 0 | 233 | | { |
| | | 234 | | // Reset the writer in exception cases as we don't want the writer.Dispose() call to flush any pendi |
| | 0 | 235 | | writer.Reset(); |
| | 0 | 236 | | writer.Dispose(); |
| | | 237 | | // On exception, walk the WriteStack for any orphaned disposables and try to dispose them. |
| | 0 | 238 | | await state.DisposePendingDisposablesOnExceptionAsync().ConfigureAwait(false); |
| | 0 | 239 | | throw; |
| | | 240 | | } |
| | | 241 | | finally |
| | | 242 | | { |
| | 0 | 243 | | writer.Dispose(); |
| | 0 | 244 | | if (pipeWriter is PooledByteBufferWriter disposable) |
| | | 245 | | { |
| | 0 | 246 | | disposable.Dispose(); |
| | | 247 | | } |
| | 0 | 248 | | } |
| | 0 | 249 | | } |
| | 0 | 250 | | } |
| | | 251 | | |
| | | 252 | | // Root serialization method for non-async streaming serialization |
| | | 253 | | internal void Serialize( |
| | | 254 | | Stream utf8Json, |
| | | 255 | | in T? rootValue, |
| | | 256 | | object? rootValueBoxed = null) |
| | 0 | 257 | | { |
| | 0 | 258 | | Debug.Assert(IsConfigured); |
| | 0 | 259 | | Debug.Assert(rootValueBoxed is null || rootValueBoxed is T); |
| | | 260 | | |
| | 0 | 261 | | if (CanUseSerializeHandlerInStreaming) |
| | 0 | 262 | | { |
| | | 263 | | // Short-circuit calls into SerializeHandler, if the `CanUseSerializeHandlerInStreaming` heuristic allow |
| | | 264 | | |
| | 0 | 265 | | Debug.Assert(SerializeHandler != null); |
| | 0 | 266 | | Debug.Assert(CanUseSerializeHandler); |
| | 0 | 267 | | Debug.Assert(Converter is JsonMetadataServicesConverter<T>); |
| | | 268 | | |
| | 0 | 269 | | Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(Options, out PooledByteBufferWriter buff |
| | | 270 | | try |
| | 0 | 271 | | { |
| | 0 | 272 | | SerializeHandler(writer, rootValue!); |
| | 0 | 273 | | writer.Flush(); |
| | 0 | 274 | | bufferWriter.WriteToStream(utf8Json); |
| | 0 | 275 | | } |
| | | 276 | | finally |
| | 0 | 277 | | { |
| | | 278 | | // Record the serialization size in both successful and failed operations, |
| | | 279 | | // since we want to immediately opt out of the fast path if it exceeds the threshold. |
| | 0 | 280 | | OnRootLevelAsyncSerializationCompleted(writer.BytesCommitted + writer.BytesPending); |
| | | 281 | | |
| | 0 | 282 | | Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, bufferWriter); |
| | 0 | 283 | | } |
| | 0 | 284 | | } |
| | 0 | 285 | | else if ( |
| | 0 | 286 | | #if NET |
| | 0 | 287 | | !typeof(T).IsValueType && |
| | 0 | 288 | | #endif |
| | 0 | 289 | | Converter.CanBePolymorphic && |
| | 0 | 290 | | rootValue is not null && |
| | 0 | 291 | | Options.TryGetPolymorphicTypeInfoForRootType(rootValue, out JsonTypeInfo? polymorphicTypeInfo)) |
| | 0 | 292 | | { |
| | 0 | 293 | | Debug.Assert(typeof(T) == typeof(object)); |
| | 0 | 294 | | polymorphicTypeInfo.SerializeAsObject(utf8Json, rootValue); |
| | 0 | 295 | | } |
| | | 296 | | else |
| | 0 | 297 | | { |
| | | 298 | | bool isFinalBlock; |
| | 0 | 299 | | WriteStack state = default; |
| | 0 | 300 | | state.Initialize(this, |
| | 0 | 301 | | rootValueBoxed, |
| | 0 | 302 | | supportContinuation: true, |
| | 0 | 303 | | supportAsync: false); |
| | | 304 | | |
| | 0 | 305 | | Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(Options, out PooledByteBufferWriter buff |
| | 0 | 306 | | Debug.Assert(bufferWriter.CanGetUnflushedBytes); |
| | | 307 | | |
| | | 308 | | try |
| | 0 | 309 | | { |
| | 0 | 310 | | state.PipeWriter = bufferWriter; |
| | 0 | 311 | | state.FlushThreshold = (int)(bufferWriter.Capacity * JsonSerializer.FlushThreshold); |
| | | 312 | | |
| | | 313 | | do |
| | 0 | 314 | | { |
| | 0 | 315 | | isFinalBlock = EffectiveConverter.WriteCore(writer, rootValue, Options, ref state); |
| | 0 | 316 | | writer.Flush(); |
| | | 317 | | |
| | 0 | 318 | | bufferWriter.WriteToStream(utf8Json); |
| | 0 | 319 | | bufferWriter.Clear(); |
| | | 320 | | |
| | 0 | 321 | | Debug.Assert(state.PendingTask == null); |
| | 0 | 322 | | } while (!isFinalBlock); |
| | | 323 | | |
| | 0 | 324 | | if (CanUseSerializeHandler) |
| | 0 | 325 | | { |
| | | 326 | | // On successful serialization, record the serialization size |
| | | 327 | | // to determine potential suitability of the type for |
| | | 328 | | // fast-path serialization in streaming methods. |
| | 0 | 329 | | Debug.Assert(writer.BytesPending == 0); |
| | 0 | 330 | | OnRootLevelAsyncSerializationCompleted(writer.BytesCommitted); |
| | 0 | 331 | | } |
| | 0 | 332 | | } |
| | | 333 | | finally |
| | 0 | 334 | | { |
| | 0 | 335 | | Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, bufferWriter); |
| | 0 | 336 | | } |
| | 0 | 337 | | } |
| | 0 | 338 | | } |
| | | 339 | | |
| | | 340 | | internal sealed override void SerializeAsObject(Utf8JsonWriter writer, object? rootValue) |
| | 0 | 341 | | => Serialize(writer, JsonSerializer.UnboxOnWrite<T>(rootValue), rootValue); |
| | | 342 | | |
| | | 343 | | internal sealed override Task SerializeAsObjectAsync(PipeWriter pipeWriter, object? rootValue, int flushThreshol |
| | 0 | 344 | | => SerializeAsync(pipeWriter, JsonSerializer.UnboxOnWrite<T>(rootValue), flushThreshold, cancellationToken, |
| | | 345 | | |
| | | 346 | | internal sealed override Task SerializeAsObjectAsync(Stream utf8Json, object? rootValue, CancellationToken cance |
| | 0 | 347 | | => SerializeAsync(utf8Json, JsonSerializer.UnboxOnWrite<T>(rootValue), cancellationToken, rootValue); |
| | | 348 | | |
| | | 349 | | internal sealed override Task SerializeAsObjectAsync(PipeWriter utf8Json, object? rootValue, CancellationToken c |
| | 0 | 350 | | => SerializeAsync(utf8Json, JsonSerializer.UnboxOnWrite<T>(rootValue), cancellationToken, rootValue); |
| | | 351 | | |
| | | 352 | | internal sealed override void SerializeAsObject(Stream utf8Json, object? rootValue) |
| | 0 | 353 | | => Serialize(utf8Json, JsonSerializer.UnboxOnWrite<T>(rootValue), rootValue); |
| | | 354 | | |
| | | 355 | | // Fast-path serialization in source gen has not been designed with streaming in mind. |
| | | 356 | | // Even though it's not used in streaming by default, we can sometimes try to turn it on |
| | | 357 | | // assuming that the current type is known to produce small enough JSON payloads. |
| | | 358 | | // The `CanUseSerializeHandlerInStreaming` flag returns true iff: |
| | | 359 | | // * The type has been used in at least `MinSerializationsSampleSize` streaming serializations AND |
| | | 360 | | // * No serialization size exceeding JsonSerializerOptions.DefaultBufferSize / 2 has been recorded so far. |
| | 0 | 361 | | private bool CanUseSerializeHandlerInStreaming => _canUseSerializeHandlerInStreamingState == 1; |
| | | 362 | | private volatile int _canUseSerializeHandlerInStreamingState; // 0: unspecified, 1: allowed, 2: forbidden |
| | | 363 | | |
| | | 364 | | private const int MinSerializationsSampleSize = 10; |
| | | 365 | | private volatile int _serializationCount; |
| | | 366 | | |
| | | 367 | | // Samples the latest serialization size for the current type to determine |
| | | 368 | | // if the fast-path SerializeHandler is appropriate for streaming serialization. |
| | | 369 | | private void OnRootLevelAsyncSerializationCompleted(long serializationSize) |
| | 0 | 370 | | { |
| | 0 | 371 | | Debug.Assert(CanUseSerializeHandler); |
| | | 372 | | |
| | 0 | 373 | | if (_canUseSerializeHandlerInStreamingState != 2) |
| | 0 | 374 | | { |
| | 0 | 375 | | if ((ulong)serializationSize > (ulong)(Options.DefaultBufferSize / 2)) |
| | 0 | 376 | | { |
| | | 377 | | // We have a serialization that exceeds the buffer size -- |
| | | 378 | | // forbid any use future use of the fast-path handler. |
| | 0 | 379 | | _canUseSerializeHandlerInStreamingState = 2; |
| | 0 | 380 | | } |
| | 0 | 381 | | else if ((uint)_serializationCount < MinSerializationsSampleSize) |
| | 0 | 382 | | { |
| | 0 | 383 | | if (Interlocked.Increment(ref _serializationCount) == MinSerializationsSampleSize) |
| | 0 | 384 | | { |
| | | 385 | | // We have the minimum number of serializations needed to flag the type as safe for fast-path. |
| | | 386 | | // Use CMPXCHG to avoid racing with threads reporting a large serialization. |
| | 0 | 387 | | Interlocked.CompareExchange(ref _canUseSerializeHandlerInStreamingState, 1, 0); |
| | 0 | 388 | | } |
| | 0 | 389 | | } |
| | 0 | 390 | | } |
| | 0 | 391 | | } |
| | | 392 | | } |
| | | 393 | | } |