Skip to content

Commit

Permalink
Merge pull request #1857 from microsoft/mk/avoid-buffering-json-data-…
Browse files Browse the repository at this point in the history
…streams

Avoid buffering JSON data into a new MemoryStream during parsing
  • Loading branch information
MaggieKimani1 authored Oct 8, 2024
2 parents 23fde05 + e0f20d0 commit 2102659
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,24 +98,27 @@ public static async Task<ReadResult> LoadAsync(Stream input, string format, Open
Utils.CheckArgumentNull(format, nameof(format));
settings ??= new OpenApiReaderSettings();

MemoryStream bufferedStream;
if (input is MemoryStream stream)
Stream preparedStream;

// Avoid buffering for JSON documents
if (input is MemoryStream || format.Equals(OpenApiConstants.Json, StringComparison.OrdinalIgnoreCase))
{
bufferedStream = stream;
preparedStream = input;
}
else
{
// Buffer stream so that OpenApiTextReaderReader can process it synchronously
// YamlDocument doesn't support async reading.
bufferedStream = new MemoryStream();
await input.CopyToAsync(bufferedStream, 81920, cancellationToken);
bufferedStream.Position = 0;
// Buffer stream for non-JSON formats (e.g., YAML) since they require synchronous reading
preparedStream = new MemoryStream();
await input.CopyToAsync(preparedStream, 81920, cancellationToken);
preparedStream.Position = 0;
}

using var reader = new StreamReader(bufferedStream, default, true, -1, settings.LeaveStreamOpen);
// Use StreamReader to process the prepared stream (buffered for YAML, direct for JSON)
using var reader = new StreamReader(preparedStream, default, true, -1, settings.LeaveStreamOpen);
return await LoadAsync(reader, format, settings, cancellationToken);
}


/// <summary>
/// Loads the TextReader input and parses it into an Open API document.
/// </summary>
Expand Down

0 comments on commit 2102659

Please sign in to comment.