Skip to content

Commit

Permalink
If the input stream is JSON, read directly from stream, otherwise buf…
Browse files Browse the repository at this point in the history
…fer it into memory
  • Loading branch information
MaggieKimani1 committed Oct 3, 2024
1 parent 7261ad9 commit e958896
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 format
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 e958896

Please sign in to comment.