Skip to content
Closed
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
2 changes: 1 addition & 1 deletion Client.Wasm/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,4 @@
}
}
}
}
}
3 changes: 2 additions & 1 deletion Client.Wasm/wwwroot/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@
}
},
"AllowedHosts": "*",
"BaseAddress": ""
"BaseAddress": "https://localhost:5001/api/vehicles"
}

21 changes: 21 additions & 0 deletions src/AppHost/AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<Sdk Name="Aspire.AppHost.Sdk" Version="9.0.0" />
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireHost>true</IsAspireHost>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.0.0" />
<PackageReference Include="Aspire.Hosting.Redis" Version="9.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\VehicleApi\VehicleApi.csproj" />
<ProjectReference Include="..\..\Client.Wasm\Client.Wasm.csproj" />
</ItemGroup>

</Project>
11 changes: 11 additions & 0 deletions src/AppHost/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddRedis("cache");

var api = builder.AddProject<Projects.VehicleApi>("vehicleapi")
.WithReference(cache);

var client = builder.AddProject<Projects.Client_Wasm>("client")
.WithReference(api);

builder.Build().Run();
17 changes: 17 additions & 0 deletions src/AppHost/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:17057;http://localhost:15057",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21057",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22057"
}
}
}
}
81 changes: 81 additions & 0 deletions src/ServiceDefaults/Extensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ServiceDiscovery;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

namespace Microsoft.Extensions.Hosting;

public static class Extensions
{
private const string HealthEndpointPath = "/health";
private const string AlivenessEndpointPath = "/alive";

public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
{
builder.ConfigureOpenTelemetry();
builder.AddDefaultHealthChecks();
builder.Services.AddServiceDiscovery();

return builder;
}

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

builder.Services.AddOpenTelemetry()
.WithMetrics(metrics => metrics
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddRuntimeInstrumentation())
.WithTracing(tracing => tracing
.AddSource(builder.Environment.ApplicationName)
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation());

builder.AddOpenTelemetryExporters();

return builder;
}

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

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

return builder;
}

public static TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
{
builder.Services.AddHealthChecks()
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);

return builder;
}

public static WebApplication MapDefaultEndpoints(this WebApplication app)
{
app.MapHealthChecks(HealthEndpointPath);
app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("live")
});

return app;
}
}
20 changes: 20 additions & 0 deletions src/ServiceDefaults/ServiceDefaults.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

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

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="8.2.2" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
</ItemGroup>

</Project>
15 changes: 15 additions & 0 deletions src/VehicleApi/Models/Vehicle.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace VehicleApi.Models;

public record Vehicle
{
public int Id { get; init; }
public string Vin { get; init; } = string.Empty;
public string Manufacturer { get; init; } = string.Empty;
public string Model { get; init; } = string.Empty;
public int Year { get; init; }
public string BodyType { get; init; } = string.Empty;
public string FuelType { get; init; } = string.Empty;
public string Color { get; init; } = string.Empty;
public double Mileage { get; init; }
public DateOnly LastServiceDate { get; init; }
}
67 changes: 67 additions & 0 deletions src/VehicleApi/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
using VehicleApi.Models;
using VehicleApi.Services;

var builder = WebApplication.CreateBuilder(args);

// Add ServiceDefaults (OpenTelemetry, health checks, service discovery)
builder.AddServiceDefaults();

// Add Redis distributed caching
builder.AddRedisDistributedCache("cache");

// Add CORS for Blazor client
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});

var app = builder.Build();

// Enable CORS
app.UseCors();

// Map health checks
app.MapDefaultEndpoints();

// API endpoint for vehicle data
app.MapGet("/api/vehicles", async (int id, IDistributedCache cache, ILogger<Program> logger) =>
{
if (id <= 0)
{
logger.LogWarning("Invalid vehicle ID {Id} requested", id);
return Results.BadRequest("ID must be greater than 0");
}

var cacheKey = $"vehicle:{id}";
var cachedData = await cache.GetAsync(cacheKey);

if (cachedData != null)
{
logger.LogInformation("Cache hit for vehicle ID {Id}", id);
var vehicle = JsonSerializer.Deserialize<Vehicle>(cachedData);
logger.LogInformation("Returning cached vehicle: {@Vehicle}", vehicle);
return Results.Ok(vehicle);
}

logger.LogInformation("Cache miss for vehicle ID {Id}", id);
var generated = VehicleGenerator.Generate(id);
logger.LogInformation("Generated new vehicle: {@Vehicle}", generated);

var serialized = JsonSerializer.SerializeToUtf8Bytes(generated);
await cache.SetAsync(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});
logger.LogInformation("Vehicle {Id} cached for 10 minutes", id);

return Results.Ok(generated);
});

app.Run();
23 changes: 23 additions & 0 deletions src/VehicleApi/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
27 changes: 27 additions & 0 deletions src/VehicleApi/Services/VehicleGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Bogus;
using VehicleApi.Models;

namespace VehicleApi.Services;

public static class VehicleGenerator
{
public static Vehicle Generate(int id)
{
// Seed per-instance (NOT global Randomizer.Seed)
var faker = new Faker<Vehicle>()
.UseSeed(id)
.RuleFor(v => v.Id, id)
.RuleFor(v => v.Vin, f => f.Vehicle.Vin())
.RuleFor(v => v.Manufacturer, f => f.Vehicle.Manufacturer())
.RuleFor(v => v.Model, f => f.Vehicle.Model())
.RuleFor(v => v.Year, f => f.Random.Int(1990, DateTime.Now.Year))
.RuleFor(v => v.BodyType, f => f.Vehicle.Type())
.RuleFor(v => v.FuelType, f => f.Vehicle.Fuel())
.RuleFor(v => v.Color, f => f.Commerce.Color())
.RuleFor(v => v.Mileage, f => f.Random.Double(0, 500000))
.RuleFor(v => v.LastServiceDate, (f, v) =>
DateOnly.FromDateTime(f.Date.Between(new DateTime(v.Year, 1, 1), DateTime.Now)));

return faker.Generate();
}
}
18 changes: 18 additions & 0 deletions src/VehicleApi/VehicleApi.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

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

<ItemGroup>
<PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="8.4.2" />
<PackageReference Include="Bogus" Version="35.6.5" />
</ItemGroup>

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

</Project>
24 changes: 24 additions & 0 deletions tests/VehicleApi.Tests/VehicleApi.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\VehicleApi\VehicleApi.csproj" />
</ItemGroup>

</Project>
Loading
Loading