diff --git a/Client.Wasm/Components/DataCard.razor b/Client.Wasm/Components/DataCard.razor index c646a839..5a3d387e 100644 --- a/Client.Wasm/Components/DataCard.razor +++ b/Client.Wasm/Components/DataCard.razor @@ -1,4 +1,4 @@ -@inject IConfiguration Configuration +@inject IConfiguration Configuration @inject HttpClient Client @@ -7,16 +7,16 @@ Характеристики текущего объекта - +
- + # Характеристика Значение - + - @if(Value is null) + @if (Value is null) { 1 @@ -30,7 +30,7 @@ foreach (var property in array) { - @(Array.IndexOf(array, property)+1) + @(Array.IndexOf(array, property) + 1) @property.Key @property.Value?.ToString() @@ -40,7 +40,7 @@
- + Запросить новый объект @@ -51,7 +51,7 @@ Идентификатор нового объекта: - + @@ -71,4 +71,4 @@ Value = await Client.GetFromJsonAsync($"{baseAddress}?id={Id}", new JsonSerializerOptions { }); StateHasChanged(); } -} +} \ No newline at end of file diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..5d311dbd 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер: №2 Балансировка нагрузки + Вариант: №44 Транспортное средство + Выполнена: Ле Лок Тхо 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..4444c8a5 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -1,4 +1,4 @@ -{ +{ "Logging": { "LogLevel": { "Default": "Information", @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7096/api/Vehicles" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..dd2450ac 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,6 +5,14 @@ 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 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vehicle.AppHost", "Vehicle.AppHost\Vehicle.AppHost.csproj", "{54CA0405-7EEA-4371-B7FC-2C28DAE084E4}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vehicle.ServiceDefaults", "Vehicle.ServiceDefaults\Vehicle.ServiceDefaults.csproj", "{FB9B2348-1D87-4A32-A4F7-ECFEBE8D694C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vehicle.Api", "Vehicle.Api\Vehicle.Api.csproj", "{A07A69BA-7257-47D7-9A72-96305089AAC1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vehicle.Gateway", "Vehicle.Gateway\Vehicle.Gateway.csproj", "{6A946D9E-A3D9-4345-929B-1415379D9102}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +23,22 @@ Global {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 + {54CA0405-7EEA-4371-B7FC-2C28DAE084E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {54CA0405-7EEA-4371-B7FC-2C28DAE084E4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {54CA0405-7EEA-4371-B7FC-2C28DAE084E4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {54CA0405-7EEA-4371-B7FC-2C28DAE084E4}.Release|Any CPU.Build.0 = Release|Any CPU + {FB9B2348-1D87-4A32-A4F7-ECFEBE8D694C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FB9B2348-1D87-4A32-A4F7-ECFEBE8D694C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FB9B2348-1D87-4A32-A4F7-ECFEBE8D694C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FB9B2348-1D87-4A32-A4F7-ECFEBE8D694C}.Release|Any CPU.Build.0 = Release|Any CPU + {A07A69BA-7257-47D7-9A72-96305089AAC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A07A69BA-7257-47D7-9A72-96305089AAC1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A07A69BA-7257-47D7-9A72-96305089AAC1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A07A69BA-7257-47D7-9A72-96305089AAC1}.Release|Any CPU.Build.0 = Release|Any CPU + {6A946D9E-A3D9-4345-929B-1415379D9102}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6A946D9E-A3D9-4345-929B-1415379D9102}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6A946D9E-A3D9-4345-929B-1415379D9102}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6A946D9E-A3D9-4345-929B-1415379D9102}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Vehicle.Api/Cache/IVehicleCache.cs b/Vehicle.Api/Cache/IVehicleCache.cs new file mode 100644 index 00000000..7f48f7e5 --- /dev/null +++ b/Vehicle.Api/Cache/IVehicleCache.cs @@ -0,0 +1,32 @@ +using Vehicle.Api.Entities; + +namespace Vehicle.Api.Cache; + +/// +/// Интерфейс для работы с кэшем транспортных средств. +/// +public interface IVehicleCache +{ + /// + /// Получает один объект из кэша по ключу. + /// + /// Ключ кэша. + /// Токен отмены операции. + /// Объект или null, если данных нет. + public Task GetOneAsync(string key, CancellationToken cancellationToken = default); + + /// + /// Сохраняет один объект в кэш. + /// + /// Ключ кэша. + /// Объект транспортного средства. + /// Время хранения в кэше. + /// Токен отмены операции. + public Task SetOneAsync( + string key, + VehicleEntity vehicle, + TimeSpan ttl, + CancellationToken cancellationToken = default); +} + + diff --git a/Vehicle.Api/Cache/RedisVehicleCache.cs b/Vehicle.Api/Cache/RedisVehicleCache.cs new file mode 100644 index 00000000..d2a21e49 --- /dev/null +++ b/Vehicle.Api/Cache/RedisVehicleCache.cs @@ -0,0 +1,54 @@ +using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; +using Vehicle.Api.Entities; + +namespace Vehicle.Api.Cache; + +/// +/// Класс для работы с Redis-кэшем транспортных средств. +/// +public class RedisVehicleCache(IDistributedCache cache) : IVehicleCache +{ + /// + /// Получает один объект из кэша по ключу. + /// + /// Ключ кэша. + /// Токен отмены операции. + /// Объект или null, если данных нет. + public async Task GetOneAsync(string key, CancellationToken cancellationToken = default) + { + var json = await cache.GetStringAsync(key, cancellationToken); + + if (string.IsNullOrWhiteSpace(json)) + { + return null; + } + + return JsonSerializer.Deserialize(json); + } + + /// + /// Сохраняет один объект в кэш. + /// + /// Ключ кэша. + /// Объект транспортного средства. + /// Время хранения в кэше. + /// Токен отмены операции. + public async Task SetOneAsync( + string key, + VehicleEntity vehicle, + TimeSpan ttl, + CancellationToken cancellationToken = default) + { + var json = JsonSerializer.Serialize(vehicle); + + await cache.SetStringAsync( + key, + json, + new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = ttl + }, + cancellationToken); + } +} \ No newline at end of file diff --git a/Vehicle.Api/Controllers/VehiclesController.cs b/Vehicle.Api/Controllers/VehiclesController.cs new file mode 100644 index 00000000..8d24a8a7 --- /dev/null +++ b/Vehicle.Api/Controllers/VehiclesController.cs @@ -0,0 +1,34 @@ +using Microsoft.AspNetCore.Mvc; +using Vehicle.Api.Entities; +using Vehicle.Api.Services; + +namespace Vehicle.Api.Controllers; + +/// +/// Контроллер для управления транспортными средствами +/// +[ApiController] +[Route("api/[controller]")] +public class VehiclesController(VehicleService vehicleService) : ControllerBase +{ + /// + /// Возвращает транспортное средство по его идентификатору + /// + /// Идентификатор транспортного средства (должен быть больше 0) + /// Токен для отмены запроса + /// Информация о найденном транспортном средстве + [HttpGet] + [ProducesResponseType(typeof(VehicleEntity), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task GetById([FromQuery] int? id, CancellationToken cancellationToken = default) + { + if (id is null || id <= 0) + { + return BadRequest("id must be > 0"); + } + + var vehicle = await vehicleService.GetByIdAsync(id.Value, cancellationToken); + return Ok(vehicle); + } + +} \ No newline at end of file diff --git a/Vehicle.Api/Entities/VehicleEntity.cs b/Vehicle.Api/Entities/VehicleEntity.cs new file mode 100644 index 00000000..37b9ca7a --- /dev/null +++ b/Vehicle.Api/Entities/VehicleEntity.cs @@ -0,0 +1,69 @@ +using System.Text.Json.Serialization; + +namespace Vehicle.Api.Entities; + +/// +/// Генератор записи о транспортных средствах +/// +public class VehicleEntity +{ + /// + /// Идентификатор в системе + /// + [JsonPropertyName("id")] + public int Id { get; set; } + + /// + /// Идентификационный номер транспортного средства (VIN-номер) + /// + [JsonPropertyName("vin")] + public string Vin { get; set; } = string.Empty; + + /// + /// Производитель + /// + [JsonPropertyName("manufacturer")] + public string Manufacturer { get; set; } = string.Empty; + + /// + /// Модель + /// + [JsonPropertyName("model")] + public string Model { get; set; } = string.Empty; + + /// + /// Год выпуска + /// + [JsonPropertyName("year")] + public int Year { get; set; } + + /// + /// Тип корпуса + /// + [JsonPropertyName("bodyType")] + public string BodyType { get; set; } = string.Empty; + + /// + /// Тип топлива + /// + [JsonPropertyName("fuelType")] + public string FuelType { get; set; } = string.Empty; + + /// + /// Цвет корпуса + /// + [JsonPropertyName("color")] + public string Color { get; set; } = string.Empty; + + /// + /// Пробег + /// + [JsonPropertyName("mileage")] + public double Mileage { get; set; } + + /// + /// Дата последнего техобслуживания + /// + [JsonPropertyName("lastServiceDate")] + public DateOnly LastServiceDate { get; set; } +} \ No newline at end of file diff --git a/Vehicle.Api/Generation/VehicleGenerator.cs b/Vehicle.Api/Generation/VehicleGenerator.cs new file mode 100644 index 00000000..6b2d1bf8 --- /dev/null +++ b/Vehicle.Api/Generation/VehicleGenerator.cs @@ -0,0 +1,39 @@ +using Bogus; +using Vehicle.Api.Entities; + +namespace Vehicle.Api.Generation; + +/// +/// Сервис генерации тестовых данных транспортного средства. +/// +public class VehicleGenerator +{ + private static readonly Faker _faker = new Faker("ru") + .RuleFor(v => v.Id, f => f.IndexFaker + 1) + .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.Date.Past(20).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 => Math.Round(f.Random.Double(0, 400000), 2)) + .RuleFor(v => v.LastServiceDate, (f, item) => + { + var productionDate = new DateTime(item.Year, 1, 1); + var serviceDate = f.Date.Between(productionDate, DateTime.Today); + return DateOnly.FromDateTime(serviceDate); + }); + + /// + /// Генерирует транспортное средство по заданному id + /// + /// Идентификатор транспортного средства + /// Сгенерированный объект транспортного средства + public VehicleEntity Generate(int id) + { + var vehicle = _faker.Generate(); + vehicle.Id = id; + return vehicle; + } +} \ No newline at end of file diff --git a/Vehicle.Api/Program.cs b/Vehicle.Api/Program.cs new file mode 100644 index 00000000..a4ab84b4 --- /dev/null +++ b/Vehicle.Api/Program.cs @@ -0,0 +1,66 @@ +using Vehicle.Api.Cache; +using Vehicle.Api.Generation; +using Vehicle.Api.Services; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Services.AddCors(options => +{ + options.AddPolicy("ClientCors", policy => + { + policy + .AllowAnyOrigin() + .WithMethods("GET") + .WithHeaders("Content-Type"); + }); +}); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +builder.AddRedisDistributedCache("redis"); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.UseCors("ClientCors"); + +app.MapGet("/", () => +{ + var instanceId = Environment.GetEnvironmentVariable("INSTANCE_ID") ?? "vehicle-api-unknown"; + + return Results.Ok(new + { + service = "Vehicle.Api", + status = "ok", + instanceId, + message = "Vehicle API is running" + }); +}); + +app.MapControllers(); + +app.Use(async (context, next) => +{ + var instanceId = Environment.GetEnvironmentVariable("INSTANCE_ID") ?? "vehicle-api-unknown"; + context.Response.Headers["X-Instance-Id"] = instanceId; + await next(); +}); + +app.Run(); \ No newline at end of file diff --git a/Vehicle.Api/Properties/launchSettings.json b/Vehicle.Api/Properties/launchSettings.json new file mode 100644 index 00000000..2c71ad7d --- /dev/null +++ b/Vehicle.Api/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:37132", + "sslPort": 44319 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5152", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7096;http://localhost:5152", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Vehicle.Api/Services/VehicleService.cs b/Vehicle.Api/Services/VehicleService.cs new file mode 100644 index 00000000..e883eacb --- /dev/null +++ b/Vehicle.Api/Services/VehicleService.cs @@ -0,0 +1,106 @@ +using System.Diagnostics; +using Vehicle.Api.Cache; +using Vehicle.Api.Entities; +using Vehicle.Api.Generation; + +namespace Vehicle.Api.Services; + +/// +/// Сервис для работы с транспортными средствами (генерация и получение по ID) +/// +public class VehicleService(VehicleGenerator generator, IVehicleCache vehicleCache, ILogger logger) +{ + /// + /// Получает транспортное средство по ID (из кэша или генерирует новое) + /// + /// Идентификатор транспортного средства + /// Токен отмены операции + /// Транспортное средство с указанным ID + public async Task GetByIdAsync( + int id, + CancellationToken cancellationToken = default) + { + var cacheKey = $"vehicle:{id}"; + var stopwatch = Stopwatch.StartNew(); + + var cachedVehicle = await TryReadCacheAsync( + () => vehicleCache.GetOneAsync(cacheKey, cancellationToken), + "Failed to read vehicle from cache. Key: {CacheKey}", + cacheKey); + + if (cachedVehicle is not null) + { + stopwatch.Stop(); + + logger.LogInformation( + "Cache hit for key {CacheKey}. Returned vehicle with id {Id} in {ElapsedMs} ms", + cacheKey, + id, + stopwatch.ElapsedMilliseconds); + + return cachedVehicle; + } + + logger.LogInformation( + "Cache miss for key {CacheKey}. Generating vehicle with id {Id}", + cacheKey, + id); + + var vehicle = generator.Generate(id); + + await TryWriteCacheAsync( + () => vehicleCache.SetOneAsync( + cacheKey, + vehicle, + TimeSpan.FromMinutes(5), + cancellationToken), + "Failed to write vehicle to cache. Key: {CacheKey}", + cacheKey); + + stopwatch.Stop(); + + logger.LogInformation( + "Generated vehicle with id {Id} in {ElapsedMs} ms", + id, + stopwatch.ElapsedMilliseconds); + + return vehicle; + } + + /// + /// Безопасно читает данные из кэша. + /// + private async Task TryReadCacheAsync( + Func> action, + string warningMessage, + string cacheKey) + { + try + { + return await action(); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogWarning(ex, warningMessage, cacheKey); + return default; + } + } + + /// + /// Безопасно записывает данные в кэш. + /// + private async Task TryWriteCacheAsync( + Func action, + string warningMessage, + string cacheKey) + { + try + { + await action(); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogWarning(ex, warningMessage, cacheKey); + } + } +} \ No newline at end of file diff --git a/Vehicle.Api/Vehicle.Api.csproj b/Vehicle.Api/Vehicle.Api.csproj new file mode 100644 index 00000000..ff3ec65b --- /dev/null +++ b/Vehicle.Api/Vehicle.Api.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + \ No newline at end of file diff --git a/Vehicle.Api/Vehicle.Api.http b/Vehicle.Api/Vehicle.Api.http new file mode 100644 index 00000000..69f05d0f --- /dev/null +++ b/Vehicle.Api/Vehicle.Api.http @@ -0,0 +1,6 @@ +@Vehicle.Api_HostAddress = https://localhost:7096 + +GET {{Vehicle.Api_HostAddress}}/api/Vehicles?id=5 +Accept: application/json + +### \ No newline at end of file diff --git a/Vehicle.Api/appsettings.Development.json b/Vehicle.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Vehicle.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Vehicle.Api/appsettings.json b/Vehicle.Api/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/Vehicle.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/Vehicle.AppHost/AppHost.cs b/Vehicle.AppHost/AppHost.cs new file mode 100644 index 00000000..4164ddfc --- /dev/null +++ b/Vehicle.AppHost/AppHost.cs @@ -0,0 +1,34 @@ +using Microsoft.Extensions.Configuration; + +var builder = DistributedApplication.CreateBuilder(args); + +var apiPorts = builder.Configuration.GetSection("ApiService:Ports").Get() + ?? throw new InvalidOperationException("ApiService:Ports is not configured."); + +var gatewayPort = builder.Configuration.GetValue("Gateway:Port") + ?? throw new InvalidOperationException("Gateway:Port is not configured."); + +var redis = builder.AddRedis("redis") + .WithRedisCommander(); + +var gateway = builder.AddProject("vehicle-gateway") + .WithHttpsEndpoint(port: gatewayPort, name: "vehicle-gateway-lb") + .WaitFor(redis); + +for (var i = 0; i < apiPorts.Length; i++) +{ + var httpsPort = apiPorts[i]; + var instanceName = $"vehicle-api-{i + 1}"; + var api = builder.AddProject($"vehicle-api-{i + 1}", launchProfileName: null) + .WithReference(redis) + .WithHttpsEndpoint(port: httpsPort, name: instanceName) + .WithEnvironment("INSTANCE_ID", instanceName) + .WaitFor(redis); + + gateway.WaitFor(api); +} + +builder.AddProject("client") + .WaitFor(gateway); + +builder.Build().Run(); \ No newline at end of file diff --git a/Vehicle.AppHost/Properties/launchSettings.json b/Vehicle.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..b14ecbd3 --- /dev/null +++ b/Vehicle.AppHost/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17080;http://localhost:15018", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21071", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22124" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15018", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19200", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20199" + } + } + } +} diff --git a/Vehicle.AppHost/Vehicle.AppHost.csproj b/Vehicle.AppHost/Vehicle.AppHost.csproj new file mode 100644 index 00000000..18a7b545 --- /dev/null +++ b/Vehicle.AppHost/Vehicle.AppHost.csproj @@ -0,0 +1,24 @@ + + + + + + Exe + net8.0 + enable + enable + 62bfc3f6-9e4a-4858-934b-e6b0454e609a + + + + + + + + + + + + + + diff --git a/Vehicle.AppHost/appsettings.Development.json b/Vehicle.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Vehicle.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Vehicle.AppHost/appsettings.json b/Vehicle.AppHost/appsettings.json new file mode 100644 index 00000000..79ba158e --- /dev/null +++ b/Vehicle.AppHost/appsettings.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "ApiService": { + "Ports": [ 7101, 7102, 7103, 7104, 7105 ] + }, + "Gateway": { + "Port": 7200 + } +} diff --git a/Vehicle.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs b/Vehicle.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs new file mode 100644 index 00000000..e0083158 --- /dev/null +++ b/Vehicle.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs @@ -0,0 +1,118 @@ +using Ocelot.LoadBalancer.Errors; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace Vehicle.Gateway.LoadBalancing; + +/// +/// Кастомный балансировщик нагрузки для Ocelot. +/// Реализует алгоритм Weighted Random через расширенный пул реплик: чем больше вес реплики, тем чаще она попадает в пул выбора. +/// +/// +/// Создаёт балансировщик и загружает веса реплик из конфигурации. +/// +/// Конфигурация приложения. +/// Функция получения доступных downstream-сервисов. +public sealed class WeightedRandomLoadBalancer(IConfiguration configuration, Func>> getServices) : ILoadBalancer +{ + private readonly Dictionary<(string Host, int Port), int> _weights = ReadWeights(configuration); + + /// + /// Имя балансировщика. + /// + public string Type => nameof(WeightedRandomLoadBalancer); + + /// + /// Выбирает downstream-сервис для текущего запроса. + /// + /// HTTP-контекст запроса. + /// Выбранный адрес downstream-сервиса. + public async Task> LeaseAsync(HttpContext _) + { + var services = await getServices(); + + if (services.Count == 0) + { + return new ErrorResponse( + new UnableToFindLoadBalancerError("No downstream services available")); + } + + var selectionPool = BuildSelectionPool(services); + + if (selectionPool.Count == 0) + { + return new ErrorResponse( + new UnableToFindLoadBalancerError("No services were added to the weighted selection pool")); + } + + var randomIndex = Random.Shared.Next(selectionPool.Count); + var selected = selectionPool[randomIndex]; + + return new OkResponse(selected); + } + + /// + /// Освобождение ресурса + /// + /// Адрес downstream-сервиса. + public void Release(ServiceHostAndPort _) { } + + /// + /// Строит расширенный пул выбора: каждая реплика добавляется в список столько раз, сколько равен её вес. + /// + /// Список доступных downstream-сервисов. + /// Расширенный пул для случайного выбора. + private List BuildSelectionPool(IEnumerable services) + { + var pool = new List(); + + foreach (var service in services) + { + var key = ( + service.HostAndPort.DownstreamHost.ToLowerInvariant(), + service.HostAndPort.DownstreamPort + ); + + var weight = _weights.GetValueOrDefault(key, 1); + weight = Math.Max(weight, 1); + + for (var i = 0; i < weight; i++) + { + pool.Add(service.HostAndPort); + } + } + + return pool; + } + + /// + /// Читает веса реплик из секции WeightedRandom:Replicas. + /// + /// Конфигурация приложения. + /// Словарь весов реплик. + private static Dictionary<(string Host, int Port), int> ReadWeights(IConfiguration configuration) + { + var result = new Dictionary<(string Host, int Port), int>(); + + foreach (var item in configuration.GetSection("WeightedRandom:Replicas").GetChildren()) + { + var endpoint = item.Key; + var separatorIndex = endpoint.LastIndexOf(':'); + + if (separatorIndex <= 0 || separatorIndex >= endpoint.Length - 1) + continue; + + var host = endpoint[..separatorIndex].Trim().ToLowerInvariant(); + var portText = endpoint[(separatorIndex + 1)..].Trim(); + + if (!int.TryParse(portText, out var port)) + continue; + if (!int.TryParse(item.Value, out var weight)) + continue; + + result[(host, port)] = Math.Max(weight, 1); + } + return result; + } +} \ No newline at end of file diff --git a/Vehicle.Gateway/Program.cs b/Vehicle.Gateway/Program.cs new file mode 100644 index 00000000..1b2eab7d --- /dev/null +++ b/Vehicle.Gateway/Program.cs @@ -0,0 +1,41 @@ +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using Vehicle.Gateway.LoadBalancing; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Configuration + .SetBasePath(builder.Environment.ContentRootPath) + .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) + .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true) + .AddEnvironmentVariables(); + +builder.Services + .AddOcelot(builder.Configuration) + .AddCustomLoadBalancer((serviceProvider, _, discoveryProvider) => + { + var configuration = serviceProvider.GetRequiredService(); + + if (discoveryProvider is null) + { + throw new InvalidOperationException("Ocelot service discovery provider is not available."); + } + + return new WeightedRandomLoadBalancer( + configuration, + discoveryProvider.GetAsync); + }); + +var app = builder.Build(); + +app.MapGet("/", () => Results.Ok(new +{ + service = "Vehicle.Gateway", + status = "ok", + message = "Gateway is running" +})); + +await app.UseOcelot(); +await app.RunAsync(); \ No newline at end of file diff --git a/Vehicle.Gateway/Properties/launchSettings.json b/Vehicle.Gateway/Properties/launchSettings.json new file mode 100644 index 00000000..306a69d3 --- /dev/null +++ b/Vehicle.Gateway/Properties/launchSettings.json @@ -0,0 +1,36 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:46271", + "sslPort": 44324 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/Vehicle.Gateway/Vehicle.Gateway.csproj b/Vehicle.Gateway/Vehicle.Gateway.csproj new file mode 100644 index 00000000..095b1747 --- /dev/null +++ b/Vehicle.Gateway/Vehicle.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/Vehicle.Gateway/appsettings.Development.json b/Vehicle.Gateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Vehicle.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Vehicle.Gateway/appsettings.json b/Vehicle.Gateway/appsettings.json new file mode 100644 index 00000000..bd7bb94d --- /dev/null +++ b/Vehicle.Gateway/appsettings.json @@ -0,0 +1,21 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Ocelot": "Information" + } + }, + + "AllowedHosts": "*", + + "WeightedRandom": { + "Replicas": { + "localhost:7101": 5, + "localhost:7102": 4, + "localhost:7103": 3, + "localhost:7104": 2, + "localhost:7105": 1 + } + } +} \ No newline at end of file diff --git a/Vehicle.Gateway/ocelot.json b/Vehicle.Gateway/ocelot.json new file mode 100644 index 00000000..bfd3ded8 --- /dev/null +++ b/Vehicle.Gateway/ocelot.json @@ -0,0 +1,38 @@ +{ + "Routes": [ + { + "UpstreamPathTemplate": "/gateway/Vehicles", + "UpstreamHttpMethod": [ "GET" ], + "DownstreamPathTemplate": "/api/Vehicles", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 7101 + }, + { + "Host": "localhost", + "Port": 7102 + }, + { + "Host": "localhost", + "Port": 7103 + }, + { + "Host": "localhost", + "Port": 7104 + }, + { + "Host": "localhost", + "Port": 7105 + } + ], + "LoadBalancerOptions": { + "Type": "WeightedRandomLoadBalancer" + } + } + ], + "GlobalConfiguration": { + "BaseUrl": "https://localhost:7200" + } +} \ No newline at end of file diff --git a/Vehicle.ServiceDefaults/Extensions.cs b/Vehicle.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..7b3daf44 --- /dev/null +++ b/Vehicle.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 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/Vehicle.ServiceDefaults/GlobalSuppressions.cs b/Vehicle.ServiceDefaults/GlobalSuppressions.cs new file mode 100644 index 00000000..b9cdf0c8 --- /dev/null +++ b/Vehicle.ServiceDefaults/GlobalSuppressions.cs @@ -0,0 +1,8 @@ +// This file is used by Code Analysis to maintain SuppressMessage +// attributes that are applied to this project. +// Project-level suppressions either have no target or are given +// a specific target and scoped to a namespace, type, member, etc. + +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage("Style", "IDE0130:Namespace does not match folder structure", Justification = "", Scope = "namespace", Target = "~N:Microsoft.Extensions.Hosting")] diff --git a/Vehicle.ServiceDefaults/Vehicle.ServiceDefaults.csproj b/Vehicle.ServiceDefaults/Vehicle.ServiceDefaults.csproj new file mode 100644 index 00000000..1b6e209a --- /dev/null +++ b/Vehicle.ServiceDefaults/Vehicle.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + +