diff --git a/API.Gateway/API.Gateway.csproj b/API.Gateway/API.Gateway.csproj new file mode 100644 index 00000000..eb6be8c3 --- /dev/null +++ b/API.Gateway/API.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + diff --git a/API.Gateway/LoadBalancers/WeightedRandom.cs b/API.Gateway/LoadBalancers/WeightedRandom.cs new file mode 100644 index 00000000..52adf782 --- /dev/null +++ b/API.Gateway/LoadBalancers/WeightedRandom.cs @@ -0,0 +1,51 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace Api.Gateway.LoadBalancers; + +/// +/// Балансировщик нагрузки на основе взвешенного случайного выбора (Weighted Random). +/// Каждой реплике назначается вероятность выбора. При поступлении запроса реплика выбирается случайно с учётом заданных вероятностей +/// +/// Фабрика для получения списка доступных сервисов +/// Конфигурация приложения +public class WeightedRandomLoadBalancer(Func>> services, IConfiguration configuration) + : ILoadBalancer +{ + private readonly double[] _cumulativeWeights = BuildCumulativeWeights( + configuration.GetSection("WeightedRandomWeights").Get() ?? [0.4, 0.3, 0.15, 0.1, 0.05]); + + public string Type => nameof(WeightedRandomLoadBalancer); + + public async Task> LeaseAsync(HttpContext httpContext) + { + var availableServices = await services(); + + if (availableServices.Count == 0) + throw new InvalidOperationException("No available downstream services"); + + var index = Array.BinarySearch(_cumulativeWeights, Random.Shared.NextDouble()); + if (index < 0) index = ~index; + + return new OkResponse( + availableServices[Math.Min(index, availableServices.Count - 1)].HostAndPort); + } + + public void Release(ServiceHostAndPort hostAndPort) { } + + /// + /// Строит массив кумулятивных весов на основе входных весов + /// + /// Веса + /// Каждый элемент результирующего массива равен сумме всех предыдущих весов включительно + private static double[] BuildCumulativeWeights(double[] weights) + { + var total = weights.Sum(); + var cumulative = new double[weights.Length]; + cumulative[0] = weights[0] / total; + for (var i = 1; i < weights.Length; i++) + cumulative[i] = cumulative[i - 1] + weights[i] / total; + return cumulative; + } +} \ No newline at end of file diff --git a/API.Gateway/Program.cs b/API.Gateway/Program.cs new file mode 100644 index 00000000..041c3a11 --- /dev/null +++ b/API.Gateway/Program.cs @@ -0,0 +1,34 @@ +using Api.Gateway.LoadBalancers; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddCors(options => +{ + options.AddPolicy("LocalPolicy", policy => + { + policy + .SetIsOriginAllowed(origin => origin.StartsWith("https://localhost")) + .WithHeaders("Content-Type") + .WithMethods("GET"); + }); +}); + +builder.Configuration + .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); + +builder.Services + .AddOcelot(builder.Configuration) + .AddCustomLoadBalancer((sp, _, discoveryProvider) => + { + var configuration = sp.GetRequiredService(); + return new WeightedRandomLoadBalancer(discoveryProvider.GetAsync, configuration); + }); + +var app = builder.Build(); + +app.UseCors("LocalPolicy"); +await app.UseOcelot(); + +await app.RunAsync(); \ No newline at end of file diff --git a/API.Gateway/Properties/launchSettings.json b/API.Gateway/Properties/launchSettings.json new file mode 100644 index 00000000..6f57f554 --- /dev/null +++ b/API.Gateway/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5296", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7270;http://localhost:5296", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/API.Gateway/appsettings.Development.json b/API.Gateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/API.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/API.Gateway/appsettings.json b/API.Gateway/appsettings.json new file mode 100644 index 00000000..30ce458b --- /dev/null +++ b/API.Gateway/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "WeightedRandomWeights": [ 0.30, 0.25, 0.20, 0.15, 0.10 ] +} diff --git a/API.Gateway/ocelot.json b/API.Gateway/ocelot.json new file mode 100644 index 00000000..d2709715 --- /dev/null +++ b/API.Gateway/ocelot.json @@ -0,0 +1,36 @@ +{ + "Routes": [ + { + "UpstreamPathTemplate": "/employee", + "UpstreamHttpMethod": [ "GET" ], + "DownstreamPathTemplate": "/employee", + "DownstreamScheme": "https", + "LoadBalancerOptions": { + "Type": "WeightedRandomLoadBalancer" + }, + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 8000 + }, + { + "Host": "localhost", + "Port": 8001 + }, + { + "Host": "localhost", + "Port": 8002 + }, + { + "Host": "localhost", + "Port": 8003 + }, + { + "Host": "localhost", + "Port": 8004 + } + ] + } + ] +} + diff --git a/Client.Wasm/Client.Wasm.csproj b/Client.Wasm/Client.Wasm.csproj index 0ba9f90c..66634ea4 100644 --- a/Client.Wasm/Client.Wasm.csproj +++ b/Client.Wasm/Client.Wasm.csproj @@ -1,7 +1,7 @@  - net8.0 + net10.0 enable enable @@ -14,8 +14,8 @@ - - + + diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..df0af0e9 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №2 "Балансировка нагрузки" + Вариант №48 "Weighted Random" + Выполнена Ненашевым Дмитрием 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..7900af49 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7270/employee" } diff --git a/Cloud.API/Cloud.API.csproj b/Cloud.API/Cloud.API.csproj new file mode 100644 index 00000000..03262b1b --- /dev/null +++ b/Cloud.API/Cloud.API.csproj @@ -0,0 +1,19 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + + + diff --git a/Cloud.API/Controllers/EmployeeController.cs b/Cloud.API/Controllers/EmployeeController.cs new file mode 100644 index 00000000..944868bb --- /dev/null +++ b/Cloud.API/Controllers/EmployeeController.cs @@ -0,0 +1,39 @@ +using Cloud.Api.Services; +using Cloud.Api.Models; +using Microsoft.AspNetCore.Mvc; + +namespace Cloud.Api.Controllers; + +/// +/// Контроллер для получения сотрудника компании по id +/// +/// Сервис получения сотрудника компании +/// Логгер +[ApiController] +[Route("employee")] +public class EmployeesController( + IEmployeeService employeeService, + ILogger logger + ) : ControllerBase +{ + /// + /// Метод для получения сотрудника компании по id + /// + /// Идентификатор сотрудника + /// Информация о сотруднике компании + /// Успешное получение сотрудника компании + /// Некорректный id сотрудника + [ProducesResponseType(typeof(Employee), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)] + [HttpGet] + public async Task> GetEmployee([FromQuery] int id) + { + if (id <= 0) + return BadRequest(new { error = "Id must be a positive number" }); + + logger.LogInformation("HTTP GET /employee, id: {employeeId}", id); + + var employee = await employeeService.GetOrGenerateAsync(id); + return Ok(employee); + } +} diff --git a/Cloud.API/Models/Employee.cs b/Cloud.API/Models/Employee.cs new file mode 100644 index 00000000..9729e095 --- /dev/null +++ b/Cloud.API/Models/Employee.cs @@ -0,0 +1,48 @@ +namespace Cloud.Api.Models; + +/// +/// Информация о сотруднике компании +/// +public class Employee +{ + /// + /// Идентификатор сотрудника в системе + /// + public required int Id { get; set; } + /// + /// ФИО + /// + public required string FullName { get; set; } + /// + /// Должность + /// + public required string Position { get; set; } + /// + /// Отдел + /// + public required string Department { get; set; } + /// + /// Дата приема + /// + public DateOnly HireDate { get; set; } + /// + /// Зарплата + /// + public required decimal Salary { get; set; } + /// + /// Электронная почта + /// + public required string Email { get; set; } + /// + /// Номер телефона + /// + public required string PhoneNumber { get; set; } + /// + /// Индикатор увольнения + /// + public required bool IsFired { get; set; } + /// + /// Дата увольнения + /// + public DateOnly? FiredDate { get; set; } +} diff --git a/Cloud.API/Program.cs b/Cloud.API/Program.cs new file mode 100644 index 00000000..146936c8 --- /dev/null +++ b/Cloud.API/Program.cs @@ -0,0 +1,28 @@ +using Cloud.Api.Services; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddSingleton(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); +app.MapControllers(); + +app.Run(); diff --git a/Cloud.API/Properties/launchSettings.json b/Cloud.API/Properties/launchSettings.json new file mode 100644 index 00000000..5704cb0e --- /dev/null +++ b/Cloud.API/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13373", + "sslPort": 44310 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5291", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7297;http://localhost:5291", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Cloud.API/Services/EmployeeGenerator.cs b/Cloud.API/Services/EmployeeGenerator.cs new file mode 100644 index 00000000..c70933bb --- /dev/null +++ b/Cloud.API/Services/EmployeeGenerator.cs @@ -0,0 +1,58 @@ +using Bogus; +using Bogus.DataSets; +using Cloud.Api.Models; +using Cloud.Api.Services; + +namespace Cloud.Api.Services; + +/// +/// Генератор сотрудника по заданному id +/// +/// Логгер +public class EmployeeGenerator( + ILogger logger + ) : IEmployeeGenerator +{ + private static readonly string[] _professions = { "Developer", "Manager", "Analyst", "Designer", "QA" }; + + private static readonly Dictionary _baseSalaryBySuffix = new() + { + ["Junior"] = 50000, + ["Middle"] = 100000, + ["Senior"] = 150000, + ["Lead"] = 200000 + }; + + private readonly Faker _faker = new Faker("ru") + .RuleFor(e => e.Id, _ => 0) + .RuleFor(e => e.FullName, f => + { + var gender = f.PickRandom(); + return $"{f.Name.LastName(gender)} {f.Name.FirstName(gender)} " + + $"{f.Name.FirstName(Name.Gender.Male)}{(gender == Name.Gender.Male ? "ович" : "овна")}"; + + }) + .RuleFor(e => e.Position, f => $"{f.PickRandom(_baseSalaryBySuffix.Keys.ToArray())} {f.PickRandom(_professions)}") + .RuleFor(e => e.Department, f => f.Commerce.Department()) + .RuleFor(e => e.HireDate, f => DateOnly.FromDateTime(f.Date.Past(10))) + .RuleFor(e => e.Salary, (f, e) => + { + var suffix = e.Position.Split(' ')[0]; + var baseSalary = _baseSalaryBySuffix.GetValueOrDefault(suffix, 70000); + return Math.Round(baseSalary + f.Random.Decimal(-5000, 25000), 2); + }) + .RuleFor(e => e.Email, (f, e) => f.Internet.Email(e.FullName)) + .RuleFor(e => e.PhoneNumber, f => f.Phone.PhoneNumber("+7(###)###-##-##")) + .RuleFor(e => e.IsFired, f => f.Random.Bool(0.2f)) + .RuleFor(e => e.FiredDate, (f, e) => + e.IsFired ? DateOnly.FromDateTime(f.Date.Between(e.HireDate.ToDateTime(TimeOnly.MinValue), DateTime.Now)) : null); + + /// + public Employee Generate(int id) + { + var employee = _faker.Generate(); + employee.Id = id; + logger.LogInformation("Generated employee with id {employeeId}", id); + return employee; + } +} \ No newline at end of file diff --git a/Cloud.API/Services/EmployeeService.cs b/Cloud.API/Services/EmployeeService.cs new file mode 100644 index 00000000..5bd6cb2c --- /dev/null +++ b/Cloud.API/Services/EmployeeService.cs @@ -0,0 +1,86 @@ +using Cloud.Api.Models; +using Cloud.Api.Services; +using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; + +namespace Cloud.Api.Services; + +/// +/// Сервис для получения сотрудника компании по id с кэшированием +/// +/// Генератор сотрудника +/// Сервис кэширования +/// Конфигурация приложения +/// Логгер +public class EmployeeService( + IEmployeeGenerator generator, + IDistributedCache cache, + IConfiguration configuration, + ILogger logger) : IEmployeeService +{ + private readonly string _cacheKeyPrefix = configuration.GetValue("CacheKeyPrefix", "employee"); + private readonly TimeSpan _cacheTtl = TimeSpan.FromMinutes(configuration.GetValue("CacheTtlMinutes", 30)); + + /// + public async Task GetOrGenerateAsync(int id) + { + var cacheKey = $"{_cacheKeyPrefix}:{id}"; + + var cached = await GetFromCache(cacheKey); + if (cached is not null) + { + return cached; + } + + logger.LogInformation("Cache miss for employee {Id}, generating new data", id); + var employee = generator.Generate(id); + await SetToCache(cacheKey, employee); + return employee; + } + + /// + /// Метод получения сотрудника из кэша + /// + /// Ключ кэша + /// + /// Сотрудник, или null в случае ошибки или отсутствия данных в кэше + /// + private async Task GetFromCache(string cacheKey) + { + try + { + var cached = await cache.GetStringAsync(cacheKey); + if (cached is null) return null; + + logger.LogInformation("Cache hit for key {CacheKey}", cacheKey); + return JsonSerializer.Deserialize(cached); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to read from cache for key {CacheKey}", cacheKey); + return null; + } + } + + /// + /// Сохранение сотрудника в кэш с обработкой ошибок при записи + /// + /// Ключ кэша + /// Сотрудник компании + private async Task SetToCache(string cacheKey, Employee employee) + { + try + { + var json = JsonSerializer.Serialize(employee); + await cache.SetStringAsync(cacheKey, json, new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheTtl + }); + logger.LogInformation("Cached employee {Id} with key {CacheKey}", employee.Id, cacheKey); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to write to cache for key {CacheKey}", cacheKey); + } + } +} \ No newline at end of file diff --git a/Cloud.API/Services/IEmployeeGenerator.cs b/Cloud.API/Services/IEmployeeGenerator.cs new file mode 100644 index 00000000..1e98d747 --- /dev/null +++ b/Cloud.API/Services/IEmployeeGenerator.cs @@ -0,0 +1,15 @@ +using Cloud.Api.Models; + +namespace Cloud.Api.Services; + +/// +/// Интерфейс генератора сотрудника компании по id +/// +public interface IEmployeeGenerator +{ + /// + /// Генерирует сотрудника компании с указанным id + /// + /// Идентификатор сотрудника компании + public Employee Generate(int id); +} \ No newline at end of file diff --git a/Cloud.API/Services/IEmployeeService.cs b/Cloud.API/Services/IEmployeeService.cs new file mode 100644 index 00000000..ffa63cb0 --- /dev/null +++ b/Cloud.API/Services/IEmployeeService.cs @@ -0,0 +1,17 @@ +using Cloud.Api.Models; + +namespace Cloud.Api.Services; + +/// +/// Интерфейс сервис для получения сотрудника компании по id с кэшированием +/// +public interface IEmployeeService +{ + /// + /// Получпет сотрудника компании по id. Если сотрудник не найден, + /// то создает нового с данным id и сохраняет его в кэше + /// + /// Идентификатор сотрудника компании + /// + public Task GetOrGenerateAsync(int id); +} diff --git a/Cloud.API/appsettings.Development.json b/Cloud.API/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Cloud.API/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Cloud.API/appsettings.json b/Cloud.API/appsettings.json new file mode 100644 index 00000000..1a7f697b --- /dev/null +++ b/Cloud.API/appsettings.json @@ -0,0 +1,11 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "CacheKeyPrefix": "employee", + "CacheTtlMinutes": 15 +} diff --git a/Cloud.AppHost/AppHost.cs b/Cloud.AppHost/AppHost.cs new file mode 100644 index 00000000..eb5220b3 --- /dev/null +++ b/Cloud.AppHost/AppHost.cs @@ -0,0 +1,20 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisInsight(containerName: "redis-insight"); + +var gateway = builder.AddProject("api-gateway"); + +for (var i = 0; i < 5; i++) +{ + var api = builder.AddProject($"api-{i}", launchProfileName: null) + .WithHttpsEndpoint(port: 8000 + i) + .WithReference(redis) + .WaitFor(redis); + gateway.WaitFor(api); +} + +var client = builder.AddProject("client") + .WaitFor(gateway); + +builder.Build().Run(); diff --git a/Cloud.AppHost/Cloud.AppHost.csproj b/Cloud.AppHost/Cloud.AppHost.csproj new file mode 100644 index 00000000..426e6be0 --- /dev/null +++ b/Cloud.AppHost/Cloud.AppHost.csproj @@ -0,0 +1,22 @@ + + + + Exe + net10.0 + enable + enable + 8ba2b54b-4ef9-4e56-9f8f-d0397cc693b5 + + + + + + + + + + + + + + diff --git a/Cloud.AppHost/Properties/launchSettings.json b/Cloud.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..c9c7dc2b --- /dev/null +++ b/Cloud.AppHost/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17080;http://localhost:15004", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21117", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23081", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22239" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15004", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19208", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18038", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20234" + } + } + } +} diff --git a/Cloud.AppHost/appsettings.Development.json b/Cloud.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Cloud.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Cloud.AppHost/appsettings.json b/Cloud.AppHost/appsettings.json new file mode 100644 index 00000000..31c092aa --- /dev/null +++ b/Cloud.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/Cloud.ServiceDefaults/Cloud.ServiceDefaults.csproj b/Cloud.ServiceDefaults/Cloud.ServiceDefaults.csproj new file mode 100644 index 00000000..aafd57a7 --- /dev/null +++ b/Cloud.ServiceDefaults/Cloud.ServiceDefaults.csproj @@ -0,0 +1,23 @@ + + + + net10.0 + enable + enable + true + + + + + + + + + + + + + + + + diff --git a/Cloud.ServiceDefaults/Extensions.cs b/Cloud.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..f1b21c13 --- /dev/null +++ b/Cloud.ServiceDefaults/Extensions.cs @@ -0,0 +1,126 @@ +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; +// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// This project should be referenced by each service project in your solution. +// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults +public static class Extensions +{ + private const string HealthEndpointPath = "/health"; + private const string AlivenessEndpointPath = "/alive"; + + public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + 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(options => + // { + // options.AllowedSchemes = ["https"]; + // }); + + return builder; + } + + public static TBuilder ConfigureOpenTelemetry(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(tracing => + // Exclude health check requests from tracing + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) + //.AddGrpcClientInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + // 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 TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + 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) + { + // 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(HealthEndpointPath); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln deleted file mode 100644 index cb48241d..00000000 --- a/CloudDevelopment.sln +++ /dev/null @@ -1,25 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.14.36811.4 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {90FE6B04-8381-437E-893A-FEBA1DA10AEE} - EndGlobalSection -EndGlobal diff --git a/CloudDevelopment.slnx b/CloudDevelopment.slnx new file mode 100644 index 00000000..dda0c1c5 --- /dev/null +++ b/CloudDevelopment.slnx @@ -0,0 +1,7 @@ + + + + + + +