Skip to content

Commit

Permalink
first break
Browse files Browse the repository at this point in the history
  • Loading branch information
Elfocrash committed May 6, 2024
1 parent 3ea1dc7 commit e56bc1e
Show file tree
Hide file tree
Showing 13 changed files with 260 additions and 17 deletions.
14 changes: 14 additions & 0 deletions CloudNativeWorkshop.sln
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,32 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
Insomnia_collection.json = Insomnia_collection.json
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dometrain.Aspire.AppHost", "src\Dometrain.Aspire.AppHost\Dometrain.Aspire.AppHost.csproj", "{77B3B2C6-A5DA-4869-A4B8-8B62C4F1616F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dometrain.Aspire.ServiceDefaults", "src\Dometrain.Aspire.ServiceDefaults\Dometrain.Aspire.ServiceDefaults.csproj", "{6B3FFFEC-B034-4408-AD34-741B02A9F163}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{BCD98E15-8F73-4F5A-8F9B-3A1BC752DB41} = {EA020C9E-BECD-40C1-98B3-48070D728500}
{77B3B2C6-A5DA-4869-A4B8-8B62C4F1616F} = {EA020C9E-BECD-40C1-98B3-48070D728500}
{6B3FFFEC-B034-4408-AD34-741B02A9F163} = {EA020C9E-BECD-40C1-98B3-48070D728500}
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BCD98E15-8F73-4F5A-8F9B-3A1BC752DB41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BCD98E15-8F73-4F5A-8F9B-3A1BC752DB41}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BCD98E15-8F73-4F5A-8F9B-3A1BC752DB41}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BCD98E15-8F73-4F5A-8F9B-3A1BC752DB41}.Release|Any CPU.Build.0 = Release|Any CPU
{77B3B2C6-A5DA-4869-A4B8-8B62C4F1616F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{77B3B2C6-A5DA-4869-A4B8-8B62C4F1616F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{77B3B2C6-A5DA-4869-A4B8-8B62C4F1616F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{77B3B2C6-A5DA-4869-A4B8-8B62C4F1616F}.Release|Any CPU.Build.0 = Release|Any CPU
{6B3FFFEC-B034-4408-AD34-741B02A9F163}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6B3FFFEC-B034-4408-AD34-741B02A9F163}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6B3FFFEC-B034-4408-AD34-741B02A9F163}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6B3FFFEC-B034-4408-AD34-741B02A9F163}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
14 changes: 7 additions & 7 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
services:
dometrain.monolith.api:
image: dometrain.monolith.api
build:
context: .
dockerfile: src/Dometrain.Monolith.Api/Dockerfile
ports:
- 8080:8080
# dometrain.monolith.api:
# image: dometrain.monolith.api
# build:
# context: .
# dockerfile: src/Dometrain.Monolith.Api/Dockerfile
# ports:
# - 8080:8080

db:
image: postgres:16.2
Expand Down
21 changes: 21 additions & 0 deletions src/Dometrain.Aspire.AppHost/Dometrain.Aspire.AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireHost>true</IsAspireHost>
<UserSecretsId>04ef7769-4a22-4b52-94e5-dd30ccee9441</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="8.0.0-preview.6.24214.1" />
<PackageReference Include="Aspire.Hosting.PostgreSQL" Version="8.0.0-preview.6.24214.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Dometrain.Monolith.Api\Dometrain.Monolith.Api.csproj" />
</ItemGroup>

</Project>
15 changes: 15 additions & 0 deletions src/Dometrain.Aspire.AppHost/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

var builder = DistributedApplication.CreateBuilder(args);

var mainDbUsername = builder.AddParameter("postgres-username");
var mainDbPassword = builder.AddParameter("postgres-password");

var mainDb = builder
.AddPostgres("main-db", mainDbUsername, mainDbPassword)
.WithDataVolume()
.AddDatabase("dometrain");

builder.AddProject<Projects.Dometrain_Monolith_Api>("dometrain-api")
.WithReference(mainDb);

builder.Build().Run();
18 changes: 18 additions & 0 deletions src/Dometrain.Aspire.AppHost/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15110",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19189",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20073",
"ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true"
}
}
}
}
8 changes: 8 additions & 0 deletions src/Dometrain.Aspire.AppHost/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
14 changes: 14 additions & 0 deletions src/Dometrain.Aspire.AppHost/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"Parameters" :
{
"postgres-username": "workshop",
"postgres-password": "changeme"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Aspire.Hosting.Dcp": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireSharedProject>true</IsAspireSharedProject>
</PropertyGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />

<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="8.3.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="8.0.0-preview.6.24214.1" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.8.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.8.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.8.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.8.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.8.0" />
</ItemGroup>

</Project>
122 changes: 122 additions & 0 deletions src/Dometrain.Aspire.ServiceDefaults/Extensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ServiceDiscovery;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

namespace Microsoft.Extensions.Hosting;

public static class Extensions
{
public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder)
{
builder.ConfigureOpenTelemetry();

builder.AddDefaultHealthChecks();

builder.Services.AddServiceDiscovery();

builder.Services.ConfigureHttpClientDefaults(http =>
{
// Turn on resilience by default
http.AddStandardResilienceHandler();

// Turn on service discovery by default
http.AddServiceDiscovery();
});

// Uncomment the following to restrict the allowed schemes for service discovery.
// builder.Services.Configure<ServiceDiscoveryOptions>(options =>
// {
// options.AllowedSchemes = ["https"];
// });

return builder;
}

public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder)
{
builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
});

builder.Services.AddOpenTelemetry()
.WithMetrics(metrics =>
{
metrics.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddRuntimeInstrumentation();
})
.WithTracing(tracing =>
{
tracing.AddAspNetCoreInstrumentation()
// Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
//.AddGrpcClientInstrumentation()
.AddHttpClientInstrumentation();
});

builder.AddOpenTelemetryExporters();

return builder;
}

private static IHostApplicationBuilder AddOpenTelemetryExporters(this IHostApplicationBuilder builder)
{
var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);

if (useOtlpExporter)
{
builder.Services.AddOpenTelemetry().UseOtlpExporter();
}

// Uncomment the following lines to enable the Prometheus exporter (requires the OpenTelemetry.Exporter.Prometheus.AspNetCore package)
// builder.Services.AddOpenTelemetry()
// .WithMetrics(metrics => metrics.AddPrometheusExporter());

// Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
//if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]))
//{
// builder.Services.AddOpenTelemetry()
// .UseAzureMonitor();
//}

return builder;
}

public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicationBuilder builder)
{
builder.Services.AddHealthChecks()
// Add a default liveness check to ensure app is responsive
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);

return builder;
}

public static WebApplication MapDefaultEndpoints(this WebApplication app)
{
// Uncomment the following line to enable the Prometheus endpoint (requires the OpenTelemetry.Exporter.Prometheus.AspNetCore package)
// app.MapPrometheusScrapingEndpoint();

// Adding health checks endpoints to applications in non-development environments has security implications.
// See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments.
if (app.Environment.IsDevelopment())
{
// All health checks must pass for app to be considered ready to accept traffic after starting
app.MapHealthChecks("/health");

// Only health checks tagged with the "live" tag must pass for app to be considered alive
app.MapHealthChecks("/alive", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("live")
});
}

return app;
}
}
9 changes: 4 additions & 5 deletions src/Dometrain.Monolith.Api/Database/DbConnectionFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,16 @@ public interface IDbConnectionFactory

public class NpgsqlConnectionFactory : IDbConnectionFactory
{
private readonly string _connectionString;
private readonly NpgsqlDataSource _dataSource;

public NpgsqlConnectionFactory(string connectionString)
public NpgsqlConnectionFactory(NpgsqlDataSource dataSource)
{
_connectionString = connectionString;
_dataSource = dataSource;
}

public async Task<IDbConnection> CreateConnectionAsync(CancellationToken token = default)
{
var connection = new NpgsqlConnection(_connectionString);
await connection.OpenAsync(token);
var connection = await _dataSource.OpenConnectionAsync(token);
return connection;
}
}
5 changes: 5 additions & 0 deletions src/Dometrain.Monolith.Api/Dometrain.Monolith.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Npgsql" Version="8.0.0-preview.6.24214.1" />
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.9.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.4" />
Expand All @@ -24,4 +25,8 @@
</Content>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Dometrain.Aspire.ServiceDefaults\Dometrain.Aspire.ServiceDefaults.csproj" />
</ItemGroup>

</Project>
12 changes: 10 additions & 2 deletions src/Dometrain.Monolith.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@
var builder = WebApplication.CreateBuilder(args);

var config = builder.Configuration;


// Aspire
builder.AddServiceDefaults();

builder.AddNpgsqlDataSource("dometrain");

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
builder.Services.AddSwaggerGen(x => x.OperationFilter<SwaggerDefaultValues>());
Expand Down Expand Up @@ -57,7 +62,7 @@
builder.Services.Configure<IdentitySettings>(builder.Configuration.GetSection(IdentitySettings.SettingsKey));

builder.Services.AddSingleton<DbInitializer>();
builder.Services.AddSingleton<IDbConnectionFactory>(_ => new NpgsqlConnectionFactory(config["Database:ConnectionString"]!));
builder.Services.AddSingleton<IDbConnectionFactory, NpgsqlConnectionFactory>();

builder.Services.AddSingleton<IPasswordHasher<Student>, PasswordHasher<Student>>();
builder.Services.AddSingleton<IIdentityService, IdentityService>();
Expand Down Expand Up @@ -85,6 +90,9 @@
app.UseSwaggerUI();
}

// Aspire
app.MapDefaultEndpoints();

app.UseExceptionHandler();

app.UseAuthentication();
Expand Down
3 changes: 0 additions & 3 deletions src/Dometrain.Monolith.Api/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
{
"Database": {
"ConnectionString": "Server=localhost;Port=5432;Database=dometrain;User ID=workshop;Password=changeme;"
},
"Identity": {
"AdminApiKey": "ThisIsAlsoMeantToBeSecret",
"Lifetime": "08:00:00",
Expand Down

0 comments on commit e56bc1e

Please sign in to comment.