-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Add APIs for OpenAPI document transformers #54935
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
7e36fe3
Add APIs for OpenAPI document transformers
captainsafia da22fdd
Address feedback
captainsafia 6d818a5
Update doc comments
captainsafia 6bf3186
Address more feedback
captainsafia 73fc68a
Handle service lifetimes correctly in activated transformers
captainsafia b7ad201
Handle disposable transformers
captainsafia 604498c
Benchmark on transformer count
captainsafia 40a9912
Fix up disposable code and improve paths perf
captainsafia a76b037
Remove unused imports in SharedTypes for RDG tests
captainsafia 578af9f
Clean up benchmarks and TryGetCachedOperationTransformerContext
captainsafia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
[assembly: BenchmarkDotNet.Attributes.AspNetCoreBenchmark] |
23 changes: 23 additions & 0 deletions
23
src/OpenApi/perf/Microsoft.AspNetCore.OpenApi.Microbenchmarks.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework> | ||
<OutputType>Exe</OutputType> | ||
<PreserveCompilationContext>true</PreserveCompilationContext> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<Reference Include="BenchmarkDotNet" /> | ||
<Reference Include="Microsoft.AspNetCore" /> | ||
<Reference Include="Microsoft.AspNetCore.OpenApi" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\test\Microsoft.AspNetCore.OpenApi.Tests.csproj" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<Compile Include="$(SharedSourceRoot)BenchmarkRunner\*.cs" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using BenchmarkDotNet.Attributes; | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.Routing; | ||
using Microsoft.OpenApi.Models; | ||
|
||
namespace Microsoft.AspNetCore.OpenApi.Microbenchmarks; | ||
|
||
/// <summary> | ||
/// The following benchmarks are used to assess the memory and performance | ||
/// impact of different types of transformers. In particular, we want to | ||
/// measure the impact of (a) context-object creation and caching and (b) | ||
/// enumerator usage when processing operations in a given document. | ||
/// </summary> | ||
public class TransformersBenchmark : OpenApiDocumentServiceTestBase | ||
{ | ||
[Params(10, 100, 1000)] | ||
public int TransformerCount { get; set; } | ||
|
||
private readonly IEndpointRouteBuilder _builder = CreateBuilder(); | ||
private readonly OpenApiOptions _options = new OpenApiOptions(); | ||
private OpenApiDocumentService _documentService; | ||
|
||
[GlobalSetup(Target = nameof(OperationTransformerAsDelegate))] | ||
public void OperationTransformerAsDelegate_Setup() | ||
{ | ||
_builder.MapGet("/", () => { }); | ||
for (var i = 0; i <= TransformerCount; i++) | ||
{ | ||
_options.UseOperationTransformer((operation, context, token) => | ||
{ | ||
operation.Description = "New Description"; | ||
return Task.CompletedTask; | ||
}); | ||
} | ||
_documentService = CreateDocumentService(_builder, _options); | ||
} | ||
|
||
[GlobalSetup(Target = nameof(ActivatedDocumentTransformer))] | ||
public void ActivatedDocumentTransformer_Setup() | ||
{ | ||
_builder.MapGet("/", () => { }); | ||
for (var i = 0; i <= TransformerCount; i++) | ||
{ | ||
_options.UseTransformer<ActivatedTransformer>(); | ||
} | ||
_documentService = CreateDocumentService(_builder, _options); | ||
} | ||
|
||
[GlobalSetup(Target = nameof(DocumentTransformerAsDelegate))] | ||
public void DocumentTransformerAsDelegate_Delegate() | ||
{ | ||
_builder.MapGet("/", () => { }); | ||
for (var i = 0; i <= TransformerCount; i++) | ||
{ | ||
_options.UseTransformer((document, context, token) => | ||
{ | ||
document.Info.Description = "New Description"; | ||
return Task.CompletedTask; | ||
}); | ||
} | ||
_documentService = CreateDocumentService(_builder, _options); | ||
} | ||
|
||
[Benchmark] | ||
public async Task OperationTransformerAsDelegate() | ||
{ | ||
await _documentService.GetOpenApiDocumentAsync(); | ||
} | ||
|
||
[Benchmark] | ||
public async Task ActivatedDocumentTransformer() | ||
{ | ||
await _documentService.GetOpenApiDocumentAsync(); | ||
} | ||
|
||
[Benchmark] | ||
public async Task DocumentTransformerAsDelegate() | ||
{ | ||
await _documentService.GetOpenApiDocumentAsync(); | ||
} | ||
|
||
private class ActivatedTransformer : IOpenApiDocumentTransformer | ||
{ | ||
public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) | ||
{ | ||
document.Info.Description = "Info Description"; | ||
return Task.CompletedTask; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 31 additions & 0 deletions
31
src/OpenApi/sample/Transformers/AddBearerSecuritySchemeTransformer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using Microsoft.AspNetCore.Authentication; | ||
using Microsoft.AspNetCore.OpenApi; | ||
using Microsoft.OpenApi.Models; | ||
|
||
namespace Sample.Transformers; | ||
|
||
public sealed class BearerSecuritySchemeTransformer(IAuthenticationSchemeProvider authenticationSchemeProvider) : IOpenApiDocumentTransformer | ||
captainsafia marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) | ||
{ | ||
var authenticationSchemes = await authenticationSchemeProvider.GetAllSchemesAsync(); | ||
if (authenticationSchemes.Any(authScheme => authScheme.Name == "Bearer")) | ||
{ | ||
var requirements = new Dictionary<string, OpenApiSecurityScheme> | ||
{ | ||
["Bearer"] = new OpenApiSecurityScheme | ||
{ | ||
Type = SecuritySchemeType.Http, | ||
Scheme = "bearer", // "bearer" refers to the header name here | ||
In = ParameterLocation.Header, | ||
BearerFormat = "Json Web Token" | ||
} | ||
}; | ||
document.Components ??= new OpenApiComponents(); | ||
document.Components.SecuritySchemes = requirements; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using Microsoft.AspNetCore.OpenApi; | ||
using Microsoft.OpenApi.Models; | ||
|
||
namespace Sample.Transformers; | ||
|
||
public sealed class AddContactTransformer : IOpenApiDocumentTransformer | ||
{ | ||
public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) | ||
{ | ||
document.Info.Contact = new OpenApiContact | ||
{ | ||
Name = "OpenAPI Enthusiast", | ||
Email = "[email protected]" | ||
captainsafia marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}; | ||
return Task.CompletedTask; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using Microsoft.AspNetCore.OpenApi; | ||
using Microsoft.OpenApi.Models; | ||
using Microsoft.OpenApi.Any; | ||
using Microsoft.OpenApi.Extensions; | ||
|
||
namespace Sample.Transformers; | ||
|
||
public static class OperationTransformers | ||
{ | ||
public static OpenApiOptions AddHeader(this OpenApiOptions options, string headerName, string defaultValue) | ||
{ | ||
return options.UseOperationTransformer((operation, context, cancellationToken) => | ||
{ | ||
var schema = OpenApiTypeMapper.MapTypeToOpenApiPrimitiveType(typeof(string)); | ||
schema.Default = new OpenApiString(defaultValue); | ||
operation.Parameters.Add(new OpenApiParameter | ||
{ | ||
Name = headerName, | ||
In = ParameterLocation.Header, | ||
Schema = schema | ||
}); | ||
return Task.CompletedTask; | ||
}); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -43,7 +43,7 @@ public static IEndpointConventionBuilder MapOpenApi(this IEndpointRouteBuilder e | |
} | ||
else | ||
{ | ||
var document = await documentService.GetOpenApiDocumentAsync(); | ||
var document = await documentService.GetOpenApiDocumentAsync(context.RequestAborted); | ||
var documentOptions = options.Get(documentName); | ||
using var output = MemoryBufferWriter.Get(); | ||
using var writer = Utf8BufferTextWriter.Get(output); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not part of this PR, but on line 53 you call |
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,37 @@ | ||
#nullable enable | ||
Microsoft.AspNetCore.Builder.OpenApiEndpointRouteBuilderExtensions | ||
Microsoft.AspNetCore.OpenApi.IOpenApiDocumentTransformer.TransformAsync(Microsoft.OpenApi.Models.OpenApiDocument! document, Microsoft.AspNetCore.OpenApi.OpenApiDocumentTransformerContext! context, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! | ||
Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext.Description.get -> Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescription! | ||
Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext.Description.init -> void | ||
Microsoft.AspNetCore.OpenApi.OpenApiOptions | ||
Microsoft.AspNetCore.OpenApi.OpenApiOptions.DocumentName.get -> string! | ||
Microsoft.AspNetCore.OpenApi.OpenApiOptions.OpenApiOptions() -> void | ||
Microsoft.AspNetCore.OpenApi.OpenApiOptions.OpenApiVersion.get -> Microsoft.OpenApi.OpenApiSpecVersion | ||
Microsoft.AspNetCore.OpenApi.OpenApiOptions.OpenApiVersion.set -> void | ||
Microsoft.AspNetCore.OpenApi.OpenApiOptions.ShouldInclude.get -> System.Func<Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescription!, bool>! | ||
Microsoft.AspNetCore.OpenApi.OpenApiOptions.ShouldInclude.set -> void | ||
Microsoft.AspNetCore.OpenApi.OpenApiOptions.UseOperationTransformer(System.Func<Microsoft.OpenApi.Models.OpenApiOperation!, Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext!, System.Threading.CancellationToken, System.Threading.Tasks.Task!>! transformer) -> Microsoft.AspNetCore.OpenApi.OpenApiOptions! | ||
Microsoft.AspNetCore.OpenApi.OpenApiOptions.UseTransformer(Microsoft.AspNetCore.OpenApi.IOpenApiDocumentTransformer! transformer) -> Microsoft.AspNetCore.OpenApi.OpenApiOptions! | ||
Microsoft.AspNetCore.OpenApi.OpenApiOptions.UseTransformer(System.Func<Microsoft.OpenApi.Models.OpenApiDocument!, Microsoft.AspNetCore.OpenApi.OpenApiDocumentTransformerContext!, System.Threading.CancellationToken, System.Threading.Tasks.Task!>! transformer) -> Microsoft.AspNetCore.OpenApi.OpenApiOptions! | ||
Microsoft.AspNetCore.OpenApi.OpenApiOptions.UseTransformer<TTransformerType>() -> Microsoft.AspNetCore.OpenApi.OpenApiOptions! | ||
Microsoft.Extensions.DependencyInjection.OpenApiServiceCollectionExtensions | ||
static Microsoft.AspNetCore.Builder.OpenApiEndpointRouteBuilderExtensions.MapOpenApi(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder! endpoints, string! pattern = "/openapi/{documentName}.json") -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! | ||
static Microsoft.Extensions.DependencyInjection.OpenApiServiceCollectionExtensions.AddOpenApi(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! | ||
static Microsoft.Extensions.DependencyInjection.OpenApiServiceCollectionExtensions.AddOpenApi(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, string! documentName) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! | ||
static Microsoft.Extensions.DependencyInjection.OpenApiServiceCollectionExtensions.AddOpenApi(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, string! documentName, System.Action<Microsoft.AspNetCore.OpenApi.OpenApiOptions!>! configureOptions) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! | ||
static Microsoft.Extensions.DependencyInjection.OpenApiServiceCollectionExtensions.AddOpenApi(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action<Microsoft.AspNetCore.OpenApi.OpenApiOptions!>! configureOptions) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! | ||
Microsoft.AspNetCore.OpenApi.IOpenApiDocumentTransformer | ||
Microsoft.AspNetCore.OpenApi.OpenApiDocumentTransformerContext | ||
Microsoft.AspNetCore.OpenApi.OpenApiDocumentTransformerContext.ApplicationServices.get -> System.IServiceProvider! | ||
Microsoft.AspNetCore.OpenApi.OpenApiDocumentTransformerContext.ApplicationServices.init -> void | ||
Microsoft.AspNetCore.OpenApi.OpenApiDocumentTransformerContext.DescriptionGroups.get -> System.Collections.Generic.IReadOnlyList<Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescriptionGroup!>! | ||
Microsoft.AspNetCore.OpenApi.OpenApiDocumentTransformerContext.DescriptionGroups.init -> void | ||
Microsoft.AspNetCore.OpenApi.OpenApiDocumentTransformerContext.DocumentName.get -> string! | ||
Microsoft.AspNetCore.OpenApi.OpenApiDocumentTransformerContext.DocumentName.init -> void | ||
Microsoft.AspNetCore.OpenApi.OpenApiDocumentTransformerContext.OpenApiDocumentTransformerContext() -> void | ||
Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext | ||
Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext.ApplicationServices.get -> System.IServiceProvider! | ||
Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext.ApplicationServices.init -> void | ||
Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext.DocumentName.get -> string! | ||
Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext.DocumentName.init -> void | ||
Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext.OpenApiOperationTransformerContext() -> void |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What were the results? Are the comparable?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Example results are below. The
OperationTransformerAsDelegate
is more allocate-y than the others because of the use of the enumerator over theOpenApiOperations
dictionary. We could optimize this but it makes the code a little less easy to read so I avoided this for now.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Don't we expect that one to be widely used? I thought the whole point of exposing the helper was so that app developers wouldn't have to roll their own. I think it might be worth a reduction in readability in this case.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I included the optimization in 40a9912. Description of it is here.
Original (with Dictionary enumerator)
Improved (with OperationType-lookup)