Skip to content
Draft
Show file tree
Hide file tree
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: 15 additions & 6 deletions src/Microsoft.OpenApi.YamlReader/OpenApiYamlReader.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

using System;
using System.IO;
using System.Text.Json.Nodes;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.OpenApi.Reader;
using SharpYaml;
using System;
using System.Text;

namespace Microsoft.OpenApi.YamlReader
{
Expand Down Expand Up @@ -58,6 +58,9 @@ public OpenApiYamlReader(OpenApiYamlReaderSettings settings)
}

/// <inheritdoc/>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <see cref="ReadResult.Diagnostic"/>.
/// </remarks>
public async Task<ReadResult> ReadAsync(Stream input,
Uri location,
OpenApiReaderSettings settings,
Expand All @@ -68,8 +71,8 @@ public async Task<ReadResult> ReadAsync(Stream input,
if (input is MemoryStream memoryStream)
{
return ReadCore(memoryStream, location, settings, cancellationToken);
}
else
}
else
{
using var preparedStream = new MemoryStream();
try
Expand All @@ -95,6 +98,9 @@ await CopyToMemoryStreamAsync(
}

/// <inheritdoc/>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <see cref="ReadResult.Diagnostic"/>.
/// </remarks>
public ReadResult Read(MemoryStream input,
Uri location,
OpenApiReaderSettings settings)
Expand All @@ -118,7 +124,7 @@ private ReadResult ReadCore(MemoryStream input,
// this represents net core, net5 and up
using var stream = new StreamReader(input, default, true, -1, settings.LeaveStreamOpen);
#else
// the implementation differs and results in a null reference exception in NETFX
// the implementation differs and results in a null reference exception in NETFX
using var stream = new StreamReader(input, Encoding.UTF8, true, 4096, settings.LeaveStreamOpen);
#endif
jsonNode = LoadJsonNodesFromYamlDocument(stream, cancellationToken);
Expand Down Expand Up @@ -194,6 +200,9 @@ public static ReadResult Read(JsonNode jsonNode, Uri location, OpenApiReaderSett
}

/// <inheritdoc/>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <paramref name="diagnostic"/>.
/// </remarks>
public T? ReadFragment<T>(MemoryStream input,
OpenApiSpecVersion version,
OpenApiDocument openApiDocument,
Expand Down
9 changes: 9 additions & 0 deletions src/Microsoft.OpenApi/Interfaces/IOpenApiReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ public interface IOpenApiReader
/// <param name="settings"> The OpenApi reader settings.</param>
/// <param name="cancellationToken">Propagates notification that an operation should be cancelled.</param>
/// <returns></returns>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <see cref="ReadResult.Diagnostic"/>.
/// </remarks>
Comment thread
baywet marked this conversation as resolved.
Resolved
Comment thread
baywet marked this conversation as resolved.
Resolved
Task<ReadResult> ReadAsync(Stream input, Uri location, OpenApiReaderSettings settings, CancellationToken cancellationToken = default);

/// <summary>
Expand All @@ -31,6 +34,9 @@ public interface IOpenApiReader
/// <param name="location">Location of where the document that is getting loaded is saved</param>
/// <param name="settings"></param>
/// <returns></returns>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <see cref="ReadResult.Diagnostic"/>.
/// </remarks>
ReadResult Read(MemoryStream input, Uri location, OpenApiReaderSettings settings);

/// <summary>
Expand All @@ -42,6 +48,9 @@ public interface IOpenApiReader
/// <param name="diagnostic">Returns diagnostic object containing errors detected during parsing.</param>
/// <param name="settings">The OpenApiReader settings.</param>
/// <returns>Instance of newly created IOpenApiElement.</returns>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <paramref name="diagnostic"/>.
/// </remarks>
T? ReadFragment<T>(MemoryStream input, OpenApiSpecVersion version, OpenApiDocument openApiDocument, out OpenApiDiagnostic diagnostic, OpenApiReaderSettings? settings = null) where T : IOpenApiElement;
}
}
30 changes: 22 additions & 8 deletions src/Microsoft.OpenApi/Models/OpenApiDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ public void RegisterComponents()
/// <summary>
/// A list of tags used by the specification with additional metadata.
/// </summary>
public ISet<OpenApiTag>? Tags
{
public ISet<OpenApiTag>? Tags
{
get
{
return _tags;
Expand Down Expand Up @@ -126,14 +126,14 @@ public ISet<OpenApiTag>? Tags
/// <summary>
/// Parameter-less constructor
/// </summary>
public OpenApiDocument()
public OpenApiDocument()
{
Workspace = new OpenApiWorkspace();
BaseUri = new(OpenApiConstants.BaseRegistryUri + Guid.NewGuid());
Info = new OpenApiInfo();
Paths = new OpenApiPaths();
}

/// <summary>
/// Initializes a copy of an an <see cref="OpenApiDocument"/> object
/// </summary>
Expand Down Expand Up @@ -528,14 +528,14 @@ private static void WriteHostInfoV2(IOpenApiWriter writer, IList<OpenApiServer>?
.ToList();

// schemes
writer.WriteOptionalCollection(OpenApiConstants.Schemes, schemes, (w, s) =>
writer.WriteOptionalCollection(OpenApiConstants.Schemes, schemes, (w, s) =>
{
if(!string.IsNullOrEmpty(s) && s is not null)
if (!string.IsNullOrEmpty(s) && s is not null)
Comment thread
baywet marked this conversation as resolved.
Dismissed
Comment thread
baywet marked this conversation as resolved.
Dismissed
{
w.WriteValue(s);
}
});
}
}
}

/// <summary>
Expand Down Expand Up @@ -733,6 +733,9 @@ private static bool TryGetPlainNameFragment(string reference, out string fragmen
/// <param name="format">The OpenAPI format to use during parsing.</param>
/// <param name="settings">The OpenApi reader settings.</param>
/// <returns></returns>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <see cref="ReadResult.Diagnostic"/>.
/// </remarks>
Comment thread
baywet marked this conversation as resolved.
Resolved
public static ReadResult Load(MemoryStream stream,
string? format = null,
OpenApiReaderSettings? settings = null)
Expand All @@ -747,6 +750,9 @@ public static ReadResult Load(MemoryStream stream,
/// <param name="settings">The OpenApi reader settings.</param>
/// <param name="token">The cancellation token</param>
/// <returns></returns>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <see cref="ReadResult.Diagnostic"/>.
/// </remarks>
public static async Task<ReadResult> LoadAsync(string url, OpenApiReaderSettings? settings = null, CancellationToken token = default)
{
return await OpenApiModelFactory.LoadAsync(url, settings, token).ConfigureAwait(false);
Expand All @@ -760,6 +766,9 @@ public static async Task<ReadResult> LoadAsync(string url, OpenApiReaderSettings
/// <param name="settings">The OpenApi reader settings.</param>
/// <param name="cancellationToken">Propagates information about operation cancelling.</param>
/// <returns></returns>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <see cref="ReadResult.Diagnostic"/>.
/// </remarks>
Comment thread
baywet marked this conversation as resolved.
Resolved
public static async Task<ReadResult> LoadAsync(Stream stream, string? format = null, OpenApiReaderSettings? settings = null, CancellationToken cancellationToken = default)
{
return await OpenApiModelFactory.LoadAsync(stream, format, settings, cancellationToken).ConfigureAwait(false);
Expand All @@ -773,6 +782,11 @@ public static async Task<ReadResult> LoadAsync(Stream stream, string? format = n
/// <param name="format"></param>
/// <param name="settings"></param>
/// <returns></returns>
/// <remarks>
/// OpenAPI semantic errors and parser errors that can be represented in the <see cref="ReadResult.Diagnostic"/> are returned.
/// Parser failures that occur before a result can be created may throw.
/// <see cref="ArgumentException"/> is thrown when <paramref name="input"/> is null or empty before parsing starts.
/// </remarks>
public static ReadResult Parse(string input,
string? format = null,
OpenApiReaderSettings? settings = null)
Expand Down Expand Up @@ -931,7 +945,7 @@ public override void Visit(IOpenApiSchema schema)
{
Schemas.Add(id, schema);
}
}
}
base.Visit(schema);
}
}
Expand Down
47 changes: 35 additions & 12 deletions src/Microsoft.OpenApi/Reader/OpenApiJsonReader.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

using System;
using System.IO;
using System.Text.Json.Nodes;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using System;

namespace Microsoft.OpenApi.Reader
{
Expand All @@ -23,6 +23,9 @@ public class OpenApiJsonReader : IOpenApiReader
/// <param name="location">Location of where the document that is getting loaded is saved</param>
/// <param name="settings">The Reader settings to be used during parsing.</param>
/// <returns></returns>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <see cref="ReadResult.Diagnostic"/>.
/// </remarks>
Comment thread
baywet marked this conversation as resolved.
Resolved
public ReadResult Read(MemoryStream input,
Uri location,
OpenApiReaderSettings settings)
Expand All @@ -39,9 +42,9 @@ public ReadResult Read(MemoryStream input,
{
jsonNode = JsonNode.Parse(input) ?? throw new InvalidOperationException($"Cannot parse input stream, {nameof(input)}.");
}
catch (JsonException ex)
catch (Exception ex) when (ex is JsonException or InvalidOperationException)
{
diagnostic.Errors.Add(new OpenApiError($"#line={ex.LineNumber}", $"Please provide the correct format, {ex.Message}"));
diagnostic.Errors.Add(CreateOpenApiError(ex, true));
diagnostic.Format = OpenApiConstants.Json;
return new ReadResult
{
Expand All @@ -60,6 +63,10 @@ public ReadResult Read(MemoryStream input,
/// <param name="location">Location of where the document that is getting loaded is saved</param>
/// <param name="settings">The Reader settings to be used during parsing.</param>
/// <returns></returns>
/// <remarks>
/// Use this overload when JSON has already been parsed into a <see cref="JsonNode"/>. OpenAPI semantic
/// errors are returned in the <see cref="ReadResult.Diagnostic"/>.
/// </remarks>
public ReadResult Read(JsonNode jsonNode,
Uri location,
OpenApiReaderSettings settings)
Expand Down Expand Up @@ -91,7 +98,7 @@ public ReadResult Read(JsonNode jsonNode,
if (document is not null && settings.RuleSet is not null && settings.RuleSet.Rules.Any())
{
var openApiErrors = document.Validate(settings.RuleSet);
if(openApiErrors is not null)
if (openApiErrors is not null)
{
foreach (var item in openApiErrors.OfType<OpenApiValidatorError>())
{
Expand All @@ -101,7 +108,7 @@ public ReadResult Read(JsonNode jsonNode,
{
diagnostic.Warnings.Add(item);
}
}
}
}
diagnostic.Format = OpenApiConstants.Json;
return new()
Expand All @@ -119,6 +126,9 @@ public ReadResult Read(JsonNode jsonNode,
/// <param name="settings">The Reader settings to be used during parsing.</param>
/// <param name="cancellationToken">Propagates notifications that operations should be cancelled.</param>
/// <returns></returns>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <see cref="ReadResult.Diagnostic"/>.
/// </remarks>
public async Task<ReadResult> ReadAsync(Stream input,
Uri location,
OpenApiReaderSettings settings,
Expand All @@ -136,9 +146,9 @@ public async Task<ReadResult> ReadAsync(Stream input,
jsonNode = await JsonNode.ParseAsync(input, cancellationToken: cancellationToken).ConfigureAwait(false) ??
throw new InvalidOperationException($"failed to parse input stream, {nameof(input)}");
}
catch (JsonException ex)
catch (Exception ex) when (ex is JsonException or InvalidOperationException)
{
diagnostic.Errors.Add(new OpenApiError($"#line={ex.LineNumber}", $"Please provide the correct format, {ex.Message}"));
diagnostic.Errors.Add(CreateOpenApiError(ex, true));
diagnostic.Format = OpenApiConstants.Json;
return new ReadResult
{
Expand All @@ -151,6 +161,9 @@ public async Task<ReadResult> ReadAsync(Stream input,
}

/// <inheritdoc/>
/// <remarks>
/// OpenAPI semantic and parser errors are returned in the <paramref name="diagnostic"/>.
/// </remarks>
Comment thread
baywet marked this conversation as resolved.
Resolved
public T? ReadFragment<T>(MemoryStream input,
OpenApiSpecVersion version,
OpenApiDocument openApiDocument,
Expand All @@ -167,16 +180,26 @@ public async Task<ReadResult> ReadAsync(Stream input,
{
jsonNode = JsonNode.Parse(input) ?? throw new InvalidOperationException($"Failed to parse stream, {nameof(input)}");
}
catch (JsonException ex)
catch (Exception ex) when (ex is JsonException or InvalidOperationException)
{
diagnostic = new();
diagnostic.Errors.Add(new($"#line={ex.LineNumber}", ex.Message));
diagnostic = new()
{
Format = OpenApiConstants.Json,
};
diagnostic.Errors.Add(CreateOpenApiError(ex, false));
return default;
}

return ReadFragment<T>(jsonNode, version, openApiDocument, out diagnostic);
}

private static OpenApiError CreateOpenApiError(Exception ex, bool includeFormatHint)
{
return ex is JsonException jsonException
? new OpenApiError($"#line={jsonException.LineNumber}", includeFormatHint ? $"Please provide the correct format, {jsonException.Message}" : jsonException.Message)
: new OpenApiError(null, ex.Message);
Comment on lines +196 to +200
}

/// <inheritdoc/>
public T? ReadFragment<T>(JsonNode input,
OpenApiSpecVersion version,
Expand Down
Loading