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
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
<ProjectReference Include="..\LittleBlocks.DependencyInjection\LittleBlocks.DependencyInjection.csproj" />
<ProjectReference Include="..\LittleBlocks.AspNetCore.Bootstrap\LittleBlocks.AspNetCore.Bootstrap.csproj" />
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// This software is part of the LittleBlocks framework
// Copyright (C) 2024 LittleBlocks
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

namespace LittleBlocks.AspNetCore.Bootstrap.UnitTests;

public class MinimalApiBootstrapperExtensionsTests
{
[Fact]
public void Should_Register_Default_MinimalApi_Services()
{
// Arrange
var builder = CreateBuilder();

// Act
var options = builder.BootstrapMinimalApi();
var provider = builder.Services.BuildServiceProvider();

// Assert
Assert.NotNull(provider.GetService<ICorrelationIdProvider>());
Assert.NotNull(provider.GetService<MinimalApiBootstrapOptions>());

var application = provider.GetRequiredService<IOptions<Application>>().Value;
Assert.Equal("TestApp", application.Name);
Assert.Equal("v1", application.Version);

Assert.Equal(ApiBootstrapperFeatures.MinimalDefaults, options.Features);
}

[Fact]
public void Should_Respect_Feature_Flags_When_Disabling_Correlation()
{
// Arrange
var builder = CreateBuilder();

// Act
builder.BootstrapMinimalApi(o =>
{
o.Features &= ~ApiBootstrapperFeatures.RequestCorrelation;
});
var provider = builder.Services.BuildServiceProvider();

// Assert
Assert.Null(provider.GetService<ICorrelationIdProvider>());
}

[Fact]
public void Should_Bind_Additional_Configuration_Sections()
{
// Arrange
var builder = CreateBuilder(new Dictionary<string, string>
{
{"CustomOptions:Enabled", "true"}
});

// Act
builder.BootstrapMinimalApi(o => o.AddSection<CustomOptions>("CustomOptions"));
var provider = builder.Services.BuildServiceProvider();

// Assert
var options = provider.GetRequiredService<IOptions<CustomOptions>>().Value;
Assert.True(options.Enabled);
}

private static WebApplicationBuilder CreateBuilder(Dictionary<string, string> additionalSettings = null)
{
var settings = new Dictionary<string, string>
{
{"Application:Name", "TestApp"},
{"Application:Version", "v1"},
{"Application:Environment:Name", "Development"},
{"AuthOptions:AuthenticationMode", "None"}
};

if (additionalSettings != null)
{
foreach (var pair in additionalSettings)
settings[pair.Key] = pair.Value;
}

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
EnvironmentName = Environments.Development,
ContentRootPath = Directory.GetCurrentDirectory()
});

builder.Configuration.AddInMemoryCollection(settings);
return builder;
}

private sealed class CustomOptions
{
public bool Enabled { get; set; }
}
}
10 changes: 9 additions & 1 deletion src/LittleBlocks.AspNetCore.Bootstrap.UnitTests/Usings.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
global using LittleBlocks.DependencyInjection;
global using LittleBlocks.DependencyInjection;
global using LittleBlocks.Http;
global using LittleBlocks.Configurations;
global using LittleBlocks.AspNetCore.Bootstrap;
global using LittleBlocks.AspNetCore.RequestCorrelation.Core;

global using Microsoft.AspNetCore.Builder;
global using Microsoft.AspNetCore.Hosting;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Options;

global using Xunit;
40 changes: 40 additions & 0 deletions src/LittleBlocks.AspNetCore.Bootstrap/ApiBootstrapperFeatures.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// This software is part of the LittleBlocks framework
// Copyright (C) 2024 LittleBlocks
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

namespace LittleBlocks.AspNetCore.Bootstrap;

[Flags]
public enum ApiBootstrapperFeatures
{
None = 0,
Configuration = 1 << 0,
RequestCorrelation = 1 << 1,
FeatureFlags = 1 << 2,
Cors = 1 << 3,
Authentication = 1 << 4,
OpenApi = 1 << 5,
HealthChecks = 1 << 6,
ExceptionHandling = 1 << 7,
Diagnostics = 1 << 8,
StaticFiles = 1 << 9,
HttpsRedirection = 1 << 10,
Controllers = 1 << 11,
StartPage = 1 << 12,
All = Configuration | RequestCorrelation | FeatureFlags | Cors | Authentication | OpenApi | HealthChecks |
ExceptionHandling | Diagnostics | StaticFiles | HttpsRedirection | Controllers | StartPage,
MinimalDefaults = All & ~Controllers,
MvcDefaults = All
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public sealed class ApiPipelineOptions(
public Action<IEndpointRouteBuilder> PostEndPointsConfigure { get; } = null;

public bool EnableStartPage { get; set; } = true;
public ApiBootstrapperFeatures Features { get; set; } = ApiBootstrapperFeatures.MvcDefaults;
public Action<IEndpointRouteBuilder, AppInfo> StartPageConfigure { get; } =
(builder, appInfo) => builder.UseStartPage(appInfo.Name);
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,43 +50,70 @@ private static void UseDefaultApiPipeline(this IApplicationBuilder app, ApiPipel
var appInfo = options.Configuration.GetApplicationInfo();
var authOptions = options.Configuration.GetAuthOptions();

if (options.Environment.IsDevelopment())
if (options.Features.HasFlag(ApiBootstrapperFeatures.ExceptionHandling))
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
if (options.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseGlobalExceptionHandler();
app.UseHsts();
}
}
else

if (options.Features.HasFlag(ApiBootstrapperFeatures.HttpsRedirection))
app.UseHttpsRedirection();

if (options.Features.HasFlag(ApiBootstrapperFeatures.StaticFiles))
app.UseStaticFiles();

if (options.Features.HasFlag(ApiBootstrapperFeatures.RequestCorrelation))
{
app.UseGlobalExceptionHandler();
app.UseHsts();
app.UseRequestCorrelation();
app.UseCorrelatedLogs();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRequestCorrelation();
app.UseCorrelatedLogs();
app.UseRouting();
app.UseCorsWithDefaultPolicy();
app.UseAuthentication();
app.UseAuthorization();

if (options.Features.HasFlag(ApiBootstrapperFeatures.Cors))
app.UseCorsWithDefaultPolicy();

if (options.Features.HasFlag(ApiBootstrapperFeatures.Authentication))
{
app.UseAuthentication();
app.UseAuthorization();
}

options.PostAuthenticationConfigure?.Invoke();

app.UseUserIdentityLogging();
app.UseDiagnostics();
app.UseOpenApiDocumentation(appInfo, u => u.ConfigureAuth(appInfo, authOptions.Authentication));

if (options.Features.HasFlag(ApiBootstrapperFeatures.Diagnostics))
app.UseDiagnostics();

if (options.Features.HasFlag(ApiBootstrapperFeatures.OpenApi))
app.UseOpenApiDocumentation(appInfo, u => u.ConfigureAuth(appInfo, authOptions.Authentication));

app.UseEndpoints(endpoints =>
{
options.PreEndPointsConfigure?.Invoke(endpoints);

endpoints.MapHealthChecks("/health", new HealthCheckOptions
if (options.Features.HasFlag(ApiBootstrapperFeatures.HealthChecks))
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
});
endpoints.MapControllers();
endpoints.MapHealthChecks("/health", new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
});
}

if (options.Features.HasFlag(ApiBootstrapperFeatures.Controllers))
endpoints.MapControllers();

if (options.EnableStartPage)
if (options.Features.HasFlag(ApiBootstrapperFeatures.StartPage) && options.EnableStartPage)
options.StartPageConfigure?.Invoke(endpoints, appInfo);

options.PostEndPointsConfigure?.Invoke(endpoints);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// This software is part of the LittleBlocks framework
// Copyright (C) 2024 LittleBlocks
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

namespace LittleBlocks.AspNetCore.Bootstrap;

public sealed class MinimalApiBootstrapOptions
{
private readonly List<Action<ConfigurationOptionBuilder>> _configurationSections =
new List<Action<ConfigurationOptionBuilder>>();

public ApiBootstrapperFeatures Features { get; set; } = ApiBootstrapperFeatures.MinimalDefaults;

public LevelOfDetails ErrorDetails { get; set; } = LevelOfDetails.StandardMessage;

public Func<IExcludeRequests, IBuildOptions> CorrelationOptions { get; set; } =
builder => builder.EnforceCorrelation();

public Action<IHealthChecksBuilder> ConfigureHealthChecks { get; set; }

public Action<IServiceCollection, IConfiguration> ConfigureServices { get; set; }

public Action<IEndpointRouteBuilder> ConfigureEndpoints { get; set; }

public Action<IEndpointRouteBuilder> PostConfigureEndpoints { get; set; }

public bool EnableStartPage { get; set; } = true;

internal IReadOnlyList<Action<ConfigurationOptionBuilder>> ConfigurationSections => _configurationSections;

internal AppInfo AppInfo { get; set; }

internal AuthOptions AuthOptions { get; set; }

public MinimalApiBootstrapOptions AddSection<TSection>() where TSection : class, new()
{
_configurationSections.Add(builder => builder.AddSection<TSection>());
return this;
}

public MinimalApiBootstrapOptions AddSection<TSection>(string sectionName) where TSection : class, new()
{
ArgumentException.ThrowIfNullOrWhiteSpace(sectionName);
_configurationSections.Add(builder => builder.AddSection<TSection>(sectionName));
return this;
}
}
Loading