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

Avoid buffering JSON data into a new MemoryStream during parsing #1857

Open
wants to merge 2 commits into
base: release/2.0.0
Choose a base branch
from
Open
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
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
Loading