From be2d775c3adc253776fdaae1e3e809c26245ab04 Mon Sep 17 00:00:00 2001 From: Vouchiko Date: Wed, 11 Mar 2026 18:20:56 +0400 Subject: [PATCH 01/10] =?UTF-8?q?=D0=A1=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD=20DT?= =?UTF-8?q?O=20=E2=80=9C=D0=A2=D0=BE=D0=B2=D0=B0=D1=80=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D1=81=D0=BA=D0=BB=D0=B0=D0=B4=D0=B5=E2=80=9D,=20=D0=BD=D0=B0?= =?UTF-8?q?=D0=BF=D0=B8=D1=81=D0=B0=D0=BD=D1=8B=20=D0=B3=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D1=80=D0=B0=D1=82=D0=BE=D1=80=20=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B?= =?UTF-8?q?=D1=85=20=D0=B8=20=D1=81=D0=B5=D1=80=D0=B2=D0=B8=D1=81=20=D1=81?= =?UTF-8?q?=20=D0=BA=D1=8D=D1=88=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=D0=BC=20=D0=B2=20Redis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Client.Wasm/Components/StudentCard.razor | 8 +- Client.Wasm/_Imports.razor | 2 +- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.sln | 18 ++++ WarehouseItem.AppHost/AppHost.cs | 14 +++ .../Properties/launchSettings.json | 29 +++++ .../WarehouseItem.AppHost.csproj | 23 ++++ .../appsettings.Development.json | 8 ++ WarehouseItem.AppHost/appsettings.json | 9 ++ .../Controller/WarehouseItemController.cs | 36 +++++++ .../DTO/WarehouseItemDTO.cs | 54 ++++++++++ .../Generator/WarehouseItemGenerator.cs | 99 +++++++++++++++++ WarehouseItem.Generator/Program.cs | 41 +++++++ .../Properties/LaunchSettings.json | 38 +++++++ .../Service/IWarehouseItemService.cs | 8 ++ .../Service/WarehouseItemService.cs | 98 +++++++++++++++++ .../WarehouseItem.Generator.csproj | 20 ++++ .../appsettings.Development.json | 8 ++ WarehouseItem.Generator/appsettings.json | 15 +++ WarehouseItem.ServiceDefaults/Extensions.cs | 100 ++++++++++++++++++ .../WarehouseItem.ServiceDefaults.csproj | 22 ++++ 21 files changed, 646 insertions(+), 6 deletions(-) create mode 100644 WarehouseItem.AppHost/AppHost.cs create mode 100644 WarehouseItem.AppHost/Properties/launchSettings.json create mode 100644 WarehouseItem.AppHost/WarehouseItem.AppHost.csproj create mode 100644 WarehouseItem.AppHost/appsettings.Development.json create mode 100644 WarehouseItem.AppHost/appsettings.json create mode 100644 WarehouseItem.Generator/Controller/WarehouseItemController.cs create mode 100644 WarehouseItem.Generator/DTO/WarehouseItemDTO.cs create mode 100644 WarehouseItem.Generator/Generator/WarehouseItemGenerator.cs create mode 100644 WarehouseItem.Generator/Program.cs create mode 100644 WarehouseItem.Generator/Properties/LaunchSettings.json create mode 100644 WarehouseItem.Generator/Service/IWarehouseItemService.cs create mode 100644 WarehouseItem.Generator/Service/WarehouseItemService.cs create mode 100644 WarehouseItem.Generator/WarehouseItem.Generator.csproj create mode 100644 WarehouseItem.Generator/appsettings.Development.json create mode 100644 WarehouseItem.Generator/appsettings.json create mode 100644 WarehouseItem.ServiceDefaults/Extensions.cs create mode 100644 WarehouseItem.ServiceDefaults/WarehouseItem.ServiceDefaults.csproj diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..5d188b50 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 "Кэширование" + Вариант №23 "Товар на складе" + Выполнена Карповым Владимиром 6512 + Ссылка на форк diff --git a/Client.Wasm/_Imports.razor b/Client.Wasm/_Imports.razor index 31e16a84..5b318dbb 100644 --- a/Client.Wasm/_Imports.razor +++ b/Client.Wasm/_Imports.razor @@ -8,7 +8,7 @@ @using Microsoft.JSInterop @using Client.Wasm.Layout @using Client.Wasm.Components -@using Blazorise +@using Blazorise @using Blazorise.Components @using System.Text.Json @using System.Text.Json.Nodes \ No newline at end of file diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..8a3e0c6c 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "http://localhost:5204/api/warehouse-item" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..5eeb6bd3 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,6 +5,12 @@ 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}") = "WarehouseItem.ServiceDefaults", "WarehouseItem.ServiceDefaults\WarehouseItem.ServiceDefaults.csproj", "{97B30C3C-3125-4E99-BA67-240DD8126A25}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseItem.Generator", "WarehouseItem.Generator\WarehouseItem.Generator.csproj", "{A9B4BB9B-9F03-4C1F-AB67-9DAD2E4D66BA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseItem.AppHost", "WarehouseItem.AppHost\WarehouseItem.AppHost.csproj", "{07AFB6CB-7359-432D-BF0B-14BA7C582AA5}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +21,18 @@ 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 + {97B30C3C-3125-4E99-BA67-240DD8126A25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {97B30C3C-3125-4E99-BA67-240DD8126A25}.Debug|Any CPU.Build.0 = Debug|Any CPU + {97B30C3C-3125-4E99-BA67-240DD8126A25}.Release|Any CPU.ActiveCfg = Release|Any CPU + {97B30C3C-3125-4E99-BA67-240DD8126A25}.Release|Any CPU.Build.0 = Release|Any CPU + {A9B4BB9B-9F03-4C1F-AB67-9DAD2E4D66BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A9B4BB9B-9F03-4C1F-AB67-9DAD2E4D66BA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A9B4BB9B-9F03-4C1F-AB67-9DAD2E4D66BA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A9B4BB9B-9F03-4C1F-AB67-9DAD2E4D66BA}.Release|Any CPU.Build.0 = Release|Any CPU + {07AFB6CB-7359-432D-BF0B-14BA7C582AA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {07AFB6CB-7359-432D-BF0B-14BA7C582AA5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {07AFB6CB-7359-432D-BF0B-14BA7C582AA5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {07AFB6CB-7359-432D-BF0B-14BA7C582AA5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/WarehouseItem.AppHost/AppHost.cs b/WarehouseItem.AppHost/AppHost.cs new file mode 100644 index 00000000..0e7fd34f --- /dev/null +++ b/WarehouseItem.AppHost/AppHost.cs @@ -0,0 +1,14 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("warehouse-item-cache") + .WithRedisInsight(containerName: "warehouse-item-insight"); + +var generator = builder.AddProject("generator") + .WithReference(cache, "warehouse-item-cache") + .WaitFor(cache); + +builder.AddProject("client") + .WithReference(generator) + .WaitFor(generator); + +builder.Build().Run(); diff --git a/WarehouseItem.AppHost/Properties/launchSettings.json b/WarehouseItem.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..330da1c2 --- /dev/null +++ b/WarehouseItem.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:17129;http://localhost:15221", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21101", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22255" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15221", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19083", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20274" + } + } + } +} \ No newline at end of file diff --git a/WarehouseItem.AppHost/WarehouseItem.AppHost.csproj b/WarehouseItem.AppHost/WarehouseItem.AppHost.csproj new file mode 100644 index 00000000..b9e8bcb5 --- /dev/null +++ b/WarehouseItem.AppHost/WarehouseItem.AppHost.csproj @@ -0,0 +1,23 @@ + + + + + + Exe + net8.0 + enable + enable + ed7e1e47-dc98-4419-8424-85412466aa9b + + + + + + + + + + + + + diff --git a/WarehouseItem.AppHost/appsettings.Development.json b/WarehouseItem.AppHost/appsettings.Development.json new file mode 100644 index 00000000..1b2d3baf --- /dev/null +++ b/WarehouseItem.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} \ No newline at end of file diff --git a/WarehouseItem.AppHost/appsettings.json b/WarehouseItem.AppHost/appsettings.json new file mode 100644 index 00000000..888f884e --- /dev/null +++ b/WarehouseItem.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} \ No newline at end of file diff --git a/WarehouseItem.Generator/Controller/WarehouseItemController.cs b/WarehouseItem.Generator/Controller/WarehouseItemController.cs new file mode 100644 index 00000000..f3cae97b --- /dev/null +++ b/WarehouseItem.Generator/Controller/WarehouseItemController.cs @@ -0,0 +1,36 @@ +using Microsoft.AspNetCore.Mvc; +using WarehouseItem.Generator.DTO; +using WarehouseItem.Generator.Service; + +namespace WarehouseItem.Generator.Controller; + +/// +/// API контроллер для работы с товарами склада. +/// +[ApiController] +[Route("api/warehouse-item")] +public sealed class WarehouseItemController(ILogger logger, IWarehouseItemService service) : ControllerBase +{ + /// + /// Получить товар по id. + /// + /// Идентификатор товара + /// Токен отмены + /// Данные товара + [HttpGet] + [ProducesResponseType(typeof(WarehouseItemDto), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task> Get([FromQuery] int id, CancellationToken cancellationToken) + { + if (id < 0) + { + return BadRequest(new { message = "id cannot be negative" }); + } + + logger.LogInformation("Request warehouse item id={id}.", id); + var dto = await service.GetAsync(id, cancellationToken); + logger.LogInformation("Response warehouse item id={id}.", id); + + return Ok(dto); + } +} diff --git a/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs b/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs new file mode 100644 index 00000000..85f7026b --- /dev/null +++ b/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs @@ -0,0 +1,54 @@ +namespace WarehouseItem.Generator.DTO; + +public sealed class WarehouseItemDto +{ + /// + /// Уникальный идентификатор товара + /// + public int Id { get; set; } + + /// + /// Название продукта + /// + public string ProductName { get; set; } = string.Empty; + + /// + /// Категория товара + /// + public string Category { get; set; } = string.Empty; + + /// + /// Количество единиц на складе + /// + public int StockQuantity { get; set; } + + /// + /// Цена за единицу товара + /// + public decimal UnitPrice { get; set; } + + /// + /// Вес одной единицы в килограммах + /// + public double UnitWeight { get; set; } + + /// + /// Размеры одной единицы товара + /// + public string UnitDimensions { get; set; } = string.Empty; + + /// + /// Флаг хрупкого товара + /// + public bool IsFragile { get; set; } + + /// + /// Дата последней поставки + /// + public DateOnly LastDeliveryDate { get; set; } + + /// + /// Дата планируемой следующей поставки + /// + public DateOnly NextDeliveryDate { get; set; } +} diff --git a/WarehouseItem.Generator/Generator/WarehouseItemGenerator.cs b/WarehouseItem.Generator/Generator/WarehouseItemGenerator.cs new file mode 100644 index 00000000..b36a7aa5 --- /dev/null +++ b/WarehouseItem.Generator/Generator/WarehouseItemGenerator.cs @@ -0,0 +1,99 @@ +using Bogus; +using WarehouseItem.Generator.DTO; + +namespace WarehouseItem.Generator.Generator; + +/// +/// Генератор тестовых данных для товаров на складе +/// +public sealed class WarehouseItemGenerator(ILogger logger) +{ + /// + /// Максимальный размер запаса товара на складе + /// + private const int MaxStockQuantity = 25000; + /// + /// Минимальная цена за единицу товара + /// + private const decimal MinUnitPrice = 5m; + /// + /// Максимальная цена за единицу товара + /// + private const decimal MaxUnitPrice = 250_000m; + /// + /// Минимальный вес единицы товара в килограммах + /// + private const double MinUnitWeight = 0.01; + /// + /// Максимальный вес единицы товара в килограммах + /// + private const double MaxUnitWeight = 250.0; + /// + /// Минимальный размер измерения в сантиметрах + /// + private const int MinDimensionCm = 1; + /// + /// Максимальный размер измерения в сантиметрах + /// + private const int MaxDimensionCm = 99; + /// + /// Максимальное количество дней назад для даты последней поставки + /// + private const int MaxLastDeliveryDaysAgo = 365; + + /// + /// Faker для генерации тестовых данных товаров + /// + private static readonly Faker_faker = new Faker("ru") + .RuleFor(x => x.ProductName, f => f.Commerce.ProductName()) + .RuleFor(x => x.Category, f => f.Commerce.Department(1)) + .RuleFor(x => x.StockQuantity, f => f.Random.Int(0, MaxStockQuantity)) + .RuleFor(x => x.UnitPrice, + f => Math.Round(f.Random.Decimal(MinUnitPrice, MaxUnitPrice), 2, MidpointRounding.AwayFromZero)) + .RuleFor(x => x.UnitWeight, + f => Math.Round(f.Random.Double(MinUnitWeight, MaxUnitWeight), 2, MidpointRounding.AwayFromZero)) + .RuleFor(x => x.UnitDimensions, f => + { + var a = f.Random.Int(MinDimensionCm, MaxDimensionCm); + var b = f.Random.Int(MinDimensionCm, MaxDimensionCm); + var c = f.Random.Int(MinDimensionCm, MaxDimensionCm); + return $"{a:D2}x{b:D2}x{c:D2} см"; + }) + .RuleFor(x => x.IsFragile, f => f.Random.Bool(0.25f)) + .RuleFor(x => x.LastDeliveryDate, f => + { + var today = DateOnly.FromDateTime(DateTime.Today); + var daysAgo = f.Random.Int(0, MaxLastDeliveryDaysAgo); + return today.AddDays(-daysAgo); + }) + .RuleFor(x => x.NextDeliveryDate, (f, dto) => dto.LastDeliveryDate.AddDays(f.Random.Int(0, 90))); + + /// + /// Генерирует случайные данные товара с указанным идентификатором + /// + /// Уникальный идентификатор товара + /// Объект WarehouseItemDto с случайно сгенерированными данными + public WarehouseItemDto Generate(int id) + { + logger.LogInformation("Generating warehouse item for id={id}", id); + + var item = _faker.Generate(); + item.Id = id; + + logger.LogInformation("Warehouse item generated: {@Item}", new + { + item.Id, + item.ProductName, + item.Category, + item.StockQuantity, + item.UnitPrice, + item.UnitWeight, + item.UnitDimensions, + item.IsFragile, + item.LastDeliveryDate, + item.NextDeliveryDate + }); + + return item; + } +} diff --git a/WarehouseItem.Generator/Program.cs b/WarehouseItem.Generator/Program.cs new file mode 100644 index 00000000..02074e9f --- /dev/null +++ b/WarehouseItem.Generator/Program.cs @@ -0,0 +1,41 @@ +using WarehouseItem.Generator.Generator; +using WarehouseItem.Generator.Service; +using WarehouseItem.ServiceDefaults; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("warehouse-item-cache"); + +builder.Services.AddCors(options => +{ + options.AddPolicy("AllowLocalDev", policy => + { + policy + .AllowAnyOrigin() + .WithHeaders("Content-Type") + .WithMethods("GET"); + }); +}); + +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +var app = builder.Build(); + +app.UseCors("AllowLocalDev"); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapControllers(); +app.MapDefaultEndpoints(); + +app.Run(); diff --git a/WarehouseItem.Generator/Properties/LaunchSettings.json b/WarehouseItem.Generator/Properties/LaunchSettings.json new file mode 100644 index 00000000..cbeaf732 --- /dev/null +++ b/WarehouseItem.Generator/Properties/LaunchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:39434", + "sslPort": 44329 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5204", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7291;http://localhost:5204", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/WarehouseItem.Generator/Service/IWarehouseItemService.cs b/WarehouseItem.Generator/Service/IWarehouseItemService.cs new file mode 100644 index 00000000..d965c5a3 --- /dev/null +++ b/WarehouseItem.Generator/Service/IWarehouseItemService.cs @@ -0,0 +1,8 @@ +using WarehouseItem.Generator.DTO; + +namespace WarehouseItem.Generator.Service; + +public interface IWarehouseItemService +{ + public Task GetAsync(int id, CancellationToken cancellationToken = default); +} diff --git a/WarehouseItem.Generator/Service/WarehouseItemService.cs b/WarehouseItem.Generator/Service/WarehouseItemService.cs new file mode 100644 index 00000000..ad65f291 --- /dev/null +++ b/WarehouseItem.Generator/Service/WarehouseItemService.cs @@ -0,0 +1,98 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Microsoft.Extensions.Caching.Distributed; +using WarehouseItem.Generator.DTO; +using WarehouseItem.Generator.Generator; + +namespace WarehouseItem.Generator.Service; + +public sealed class WarehouseItemService( + ILogger logger, + WarehouseItemGenerator generator, + IDistributedCache cache, + IConfiguration configuration) : IWarehouseItemService +{ + private const string CacheKeyPrefix = "warehouse-item:"; + private const int CacheExpirationTimeMinutesDefault = 15; + + private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web) + { + DefaultIgnoreCondition = JsonIgnoreCondition.Never + }; + + private readonly TimeSpan _cacheTtl = TimeSpan.FromMinutes( + configuration.GetValue("CacheSettings:ExpirationTimeMinutes", CacheExpirationTimeMinutesDefault)); + + public async Task GetAsync(int id, CancellationToken cancellationToken = default) + { + var cacheKey = $"{CacheKeyPrefix}{id}"; + + var cached = await TryReadCacheAsync(cacheKey, cancellationToken); + if (cached is not null) + { + return cached; + } + + var generated = generator.Generate(id); + await TryWriteCacheAsync(cacheKey, generated, cancellationToken); + + return generated; + } + + private async Task TryReadCacheAsync(string cacheKey, CancellationToken cancellationToken) + { + string? json; + try + { + json = await cache.GetStringAsync(cacheKey, cancellationToken); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Cache read failed for key={cacheKey}.", cacheKey); + return null; + } + + if (string.IsNullOrWhiteSpace(json)) + { + logger.LogInformation("Cache miss for key={cacheKey}.", cacheKey); + return null; + } + + try + { + var obj = JsonSerializer.Deserialize(json, _jsonOptions); + if (obj is null) + { + logger.LogWarning("Cache value for key={cacheKey} deserialized as null.", cacheKey); + return null; + } + + logger.LogInformation("Cache hit for id={id}.", obj.Id); + return obj; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Cache JSON invalid for key={cacheKey}.", cacheKey); + return null; + } + } + + private async Task TryWriteCacheAsync(string cacheKey, WarehouseItemDto value, CancellationToken cancellationToken) + { + try + { + var options = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheTtl + }; + + var json = JsonSerializer.Serialize(value, _jsonOptions); + await cache.SetStringAsync(cacheKey, json, options, cancellationToken); + logger.LogInformation("Cached id={id} for ttl={ttlMinutes}m.", value.Id, _cacheTtl.TotalMinutes); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Cache write failed for id={id}.", value.Id); + } + } +} diff --git a/WarehouseItem.Generator/WarehouseItem.Generator.csproj b/WarehouseItem.Generator/WarehouseItem.Generator.csproj new file mode 100644 index 00000000..1883551f --- /dev/null +++ b/WarehouseItem.Generator/WarehouseItem.Generator.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + enable + enable + WarehouseItem.Generator + + + + + + + + + + + + + diff --git a/WarehouseItem.Generator/appsettings.Development.json b/WarehouseItem.Generator/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/WarehouseItem.Generator/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/WarehouseItem.Generator/appsettings.json b/WarehouseItem.Generator/appsettings.json new file mode 100644 index 00000000..98599fad --- /dev/null +++ b/WarehouseItem.Generator/appsettings.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "WarehouseItemCache": { + "AbsoluteExpirationSeconds": 300 + }, + "ConnectionStrings": { + "redis": "" + }, + "AllowedHosts": "*" +} diff --git a/WarehouseItem.ServiceDefaults/Extensions.cs b/WarehouseItem.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..e1fe3ef1 --- /dev/null +++ b/WarehouseItem.ServiceDefaults/Extensions.cs @@ -0,0 +1,100 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace WarehouseItem.ServiceDefaults; + +// Common cross-service wiring for Aspire: telemetry, health checks, service discovery, and resilient HttpClient. +public static class Extensions +{ + private const string ReadyPath = "/health"; + private const string AlivePath = "/alive"; + private const string LiveTag = "live"; + + public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.AddDefaultHealthChecks(); + builder.ConfigureOpenTelemetry(); + builder.Services.AddServiceDiscovery(); + builder.Services.ConfigureHttpClientDefaults(static http => + { + http.AddStandardResilienceHandler(); + http.AddServiceDiscovery(); + }); + + return builder; + } + + public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Logging.AddOpenTelemetry(static logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(static metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddSource(builder.Environment.ApplicationName) + .AddAspNetCoreInstrumentation(options => + { + options.Filter = (HttpContext context) => !IsHealthRequest(context.Request.Path); + }) + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + var otlpEndpoint = builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]; + if (!string.IsNullOrWhiteSpace(otlpEndpoint)) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + return builder; + } + + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Services.AddHealthChecks() + .AddCheck("self", () => HealthCheckResult.Healthy(), new[] { LiveTag }); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + if (app.Environment.IsDevelopment()) + { + app.MapHealthChecks(ReadyPath); + app.MapHealthChecks(AlivePath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains(LiveTag) + }); + } + + return app; + } + + private static bool IsHealthRequest(PathString path) + => path.StartsWithSegments(ReadyPath) || path.StartsWithSegments(AlivePath); +} diff --git a/WarehouseItem.ServiceDefaults/WarehouseItem.ServiceDefaults.csproj b/WarehouseItem.ServiceDefaults/WarehouseItem.ServiceDefaults.csproj new file mode 100644 index 00000000..230756f9 --- /dev/null +++ b/WarehouseItem.ServiceDefaults/WarehouseItem.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + \ No newline at end of file From 3f061945997544c0f39b30b0b6d17f158f1006bc Mon Sep 17 00:00:00 2001 From: Vouchiko Date: Fri, 13 Mar 2026 19:20:39 +0400 Subject: [PATCH 02/10] some fixes --- WarehouseItem.AppHost/AppHost.cs | 1 - .../WarehouseItem.AppHost.csproj | 6 +- .../DTO/WarehouseItemDTO.cs | 3 + WarehouseItem.Generator/Program.cs | 1 + .../Service/IWarehouseItemCache.cs | 27 +++++ .../Service/IWarehouseItemService.cs | 10 ++ .../Service/WarehouseItemCache.cs | 103 ++++++++++++++++++ .../Service/WarehouseItemService.cs | 90 ++------------- .../WarehouseItem.Generator.csproj | 2 +- WarehouseItem.Generator/appsettings.json | 3 - 10 files changed, 160 insertions(+), 86 deletions(-) create mode 100644 WarehouseItem.Generator/Service/IWarehouseItemCache.cs create mode 100644 WarehouseItem.Generator/Service/WarehouseItemCache.cs diff --git a/WarehouseItem.AppHost/AppHost.cs b/WarehouseItem.AppHost/AppHost.cs index 0e7fd34f..77d7c835 100644 --- a/WarehouseItem.AppHost/AppHost.cs +++ b/WarehouseItem.AppHost/AppHost.cs @@ -8,7 +8,6 @@ .WaitFor(cache); builder.AddProject("client") - .WithReference(generator) .WaitFor(generator); builder.Build().Run(); diff --git a/WarehouseItem.AppHost/WarehouseItem.AppHost.csproj b/WarehouseItem.AppHost/WarehouseItem.AppHost.csproj index b9e8bcb5..2550d0e2 100644 --- a/WarehouseItem.AppHost/WarehouseItem.AppHost.csproj +++ b/WarehouseItem.AppHost/WarehouseItem.AppHost.csproj @@ -1,6 +1,6 @@ - + Exe @@ -11,8 +11,8 @@ - - + + diff --git a/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs b/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs index 85f7026b..dc954c7b 100644 --- a/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs +++ b/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs @@ -1,5 +1,8 @@ namespace WarehouseItem.Generator.DTO; +/// +/// DTO для передачи данных о товаре на складе, включая идентификатор, название, категорию, количество, цену и другие характеристики. +/// public sealed class WarehouseItemDto { /// diff --git a/WarehouseItem.Generator/Program.cs b/WarehouseItem.Generator/Program.cs index 02074e9f..0d3c04ee 100644 --- a/WarehouseItem.Generator/Program.cs +++ b/WarehouseItem.Generator/Program.cs @@ -19,6 +19,7 @@ }); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddControllers(); diff --git a/WarehouseItem.Generator/Service/IWarehouseItemCache.cs b/WarehouseItem.Generator/Service/IWarehouseItemCache.cs new file mode 100644 index 00000000..845a9dc1 --- /dev/null +++ b/WarehouseItem.Generator/Service/IWarehouseItemCache.cs @@ -0,0 +1,27 @@ +using System.Threading; +using System.Threading.Tasks; +using WarehouseItem.Generator.DTO; + +namespace WarehouseItem.Generator.Service; + +/// +/// Интерфейс для кэширования товаров. +/// +public interface IWarehouseItemCache +{ + /// + /// Получить товар из кэша по идентификатору. + /// + /// Идентификатор товара. + /// Токен отмены. + /// DTO товара или null, если не найден в кэше. + public Task GetAsync(int id, CancellationToken cancellationToken = default); + + /// + /// Сохранить товар в кэш. + /// + /// Идентификатор товара. + /// DTO товара для сохранения. + /// Токен отмены. + public Task SetAsync(int id, WarehouseItemDto value, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/WarehouseItem.Generator/Service/IWarehouseItemService.cs b/WarehouseItem.Generator/Service/IWarehouseItemService.cs index d965c5a3..1ca1055f 100644 --- a/WarehouseItem.Generator/Service/IWarehouseItemService.cs +++ b/WarehouseItem.Generator/Service/IWarehouseItemService.cs @@ -1,8 +1,18 @@ +using System.Threading.Tasks; using WarehouseItem.Generator.DTO; namespace WarehouseItem.Generator.Service; +/// +/// Интерфейс для сервиса работы с товарами на складе. +/// public interface IWarehouseItemService { + /// + /// Получить товар по идентификатору. + /// + /// Идентификатор товара. + /// Токен отмены. + /// DTO товара. public Task GetAsync(int id, CancellationToken cancellationToken = default); } diff --git a/WarehouseItem.Generator/Service/WarehouseItemCache.cs b/WarehouseItem.Generator/Service/WarehouseItemCache.cs new file mode 100644 index 00000000..fe98b00e --- /dev/null +++ b/WarehouseItem.Generator/Service/WarehouseItemCache.cs @@ -0,0 +1,103 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using WarehouseItem.Generator.DTO; + +namespace WarehouseItem.Generator.Service; + +/// +/// Реализация кэширования товаров с использованием распределенного кэша. +/// +public sealed class WarehouseItemCache( + ILogger logger, + IDistributedCache cache, + IConfiguration configuration) : IWarehouseItemCache +{ + private const string CacheKeyPrefix = "warehouse-item:"; + private const int CacheExpirationTimeMinutesDefault = 15; + + private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web) + { + DefaultIgnoreCondition = JsonIgnoreCondition.Never + }; + + private readonly TimeSpan _cacheTtl = TimeSpan.FromMinutes( + configuration.GetValue("CacheSettings:ExpirationTimeMinutes", CacheExpirationTimeMinutesDefault)); + + /// + /// Получить товар из кэша по идентификатору. + /// + /// Идентификатор товара. + /// Токен отмены. + /// DTO товара или null, если не найден в кэше. + public async Task GetAsync(int id, CancellationToken cancellationToken = default) + { + var cacheKey = $"{CacheKeyPrefix}{id}"; + + string? json; + try + { + json = await cache.GetStringAsync(cacheKey, cancellationToken); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Cache read failed for key={cacheKey}.", cacheKey); + return null; + } + + if (string.IsNullOrWhiteSpace(json)) + { + logger.LogInformation("Cache miss for key={cacheKey}.", cacheKey); + return null; + } + + try + { + var obj = JsonSerializer.Deserialize(json, _jsonOptions); + if (obj is null) + { + logger.LogWarning("Cache value for key={cacheKey} deserialized as null.", cacheKey); + return null; + } + + logger.LogInformation("Cache hit for id={id}.", obj.Id); + return obj; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Cache JSON invalid for key={cacheKey}.", cacheKey); + return null; + } + } + + /// + /// Сохранить товар в кэш. + /// + /// Идентификатор товара. + /// DTO товара для сохранения. + /// Токен отмены. + public async Task SetAsync(int id, WarehouseItemDto value, CancellationToken cancellationToken = default) + { + var cacheKey = $"{CacheKeyPrefix}{id}"; + + try + { + var options = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheTtl + }; + + var json = JsonSerializer.Serialize(value, _jsonOptions); + await cache.SetStringAsync(cacheKey, json, options, cancellationToken); + logger.LogInformation("Cached id={id} for ttl={ttlMinutes}m.", value.Id, _cacheTtl.TotalMinutes); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Cache write failed for id={id}.", value.Id); + } + } +} \ No newline at end of file diff --git a/WarehouseItem.Generator/Service/WarehouseItemService.cs b/WarehouseItem.Generator/Service/WarehouseItemService.cs index ad65f291..23dcf713 100644 --- a/WarehouseItem.Generator/Service/WarehouseItemService.cs +++ b/WarehouseItem.Generator/Service/WarehouseItemService.cs @@ -1,98 +1,32 @@ -using System.Text.Json; -using System.Text.Json.Serialization; -using Microsoft.Extensions.Caching.Distributed; using WarehouseItem.Generator.DTO; using WarehouseItem.Generator.Generator; namespace WarehouseItem.Generator.Service; +/// +/// Реализация сервиса работы с товарами на складе. +/// public sealed class WarehouseItemService( - ILogger logger, WarehouseItemGenerator generator, - IDistributedCache cache, - IConfiguration configuration) : IWarehouseItemService + IWarehouseItemCache cache) : IWarehouseItemService { - private const string CacheKeyPrefix = "warehouse-item:"; - private const int CacheExpirationTimeMinutesDefault = 15; - - private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web) - { - DefaultIgnoreCondition = JsonIgnoreCondition.Never - }; - - private readonly TimeSpan _cacheTtl = TimeSpan.FromMinutes( - configuration.GetValue("CacheSettings:ExpirationTimeMinutes", CacheExpirationTimeMinutesDefault)); - + /// + /// Получить товар по идентификатору. Если товар не найден в кэше, генерирует новый и сохраняет в кэш. + /// + /// Идентификатор товара. + /// Токен отмены. + /// DTO товара. public async Task GetAsync(int id, CancellationToken cancellationToken = default) { - var cacheKey = $"{CacheKeyPrefix}{id}"; - - var cached = await TryReadCacheAsync(cacheKey, cancellationToken); + var cached = await cache.GetAsync(id, cancellationToken); if (cached is not null) { return cached; } var generated = generator.Generate(id); - await TryWriteCacheAsync(cacheKey, generated, cancellationToken); + await cache.SetAsync(id, generated, cancellationToken); return generated; } - - private async Task TryReadCacheAsync(string cacheKey, CancellationToken cancellationToken) - { - string? json; - try - { - json = await cache.GetStringAsync(cacheKey, cancellationToken); - } - catch (Exception ex) - { - logger.LogWarning(ex, "Cache read failed for key={cacheKey}.", cacheKey); - return null; - } - - if (string.IsNullOrWhiteSpace(json)) - { - logger.LogInformation("Cache miss for key={cacheKey}.", cacheKey); - return null; - } - - try - { - var obj = JsonSerializer.Deserialize(json, _jsonOptions); - if (obj is null) - { - logger.LogWarning("Cache value for key={cacheKey} deserialized as null.", cacheKey); - return null; - } - - logger.LogInformation("Cache hit for id={id}.", obj.Id); - return obj; - } - catch (Exception ex) - { - logger.LogWarning(ex, "Cache JSON invalid for key={cacheKey}.", cacheKey); - return null; - } - } - - private async Task TryWriteCacheAsync(string cacheKey, WarehouseItemDto value, CancellationToken cancellationToken) - { - try - { - var options = new DistributedCacheEntryOptions - { - AbsoluteExpirationRelativeToNow = _cacheTtl - }; - - var json = JsonSerializer.Serialize(value, _jsonOptions); - await cache.SetStringAsync(cacheKey, json, options, cancellationToken); - logger.LogInformation("Cached id={id} for ttl={ttlMinutes}m.", value.Id, _cacheTtl.TotalMinutes); - } - catch (Exception ex) - { - logger.LogWarning(ex, "Cache write failed for id={id}.", value.Id); - } - } } diff --git a/WarehouseItem.Generator/WarehouseItem.Generator.csproj b/WarehouseItem.Generator/WarehouseItem.Generator.csproj index 1883551f..d345185d 100644 --- a/WarehouseItem.Generator/WarehouseItem.Generator.csproj +++ b/WarehouseItem.Generator/WarehouseItem.Generator.csproj @@ -9,7 +9,7 @@ - + diff --git a/WarehouseItem.Generator/appsettings.json b/WarehouseItem.Generator/appsettings.json index 98599fad..3af4bd71 100644 --- a/WarehouseItem.Generator/appsettings.json +++ b/WarehouseItem.Generator/appsettings.json @@ -8,8 +8,5 @@ "WarehouseItemCache": { "AbsoluteExpirationSeconds": 300 }, - "ConnectionStrings": { - "redis": "" - }, "AllowedHosts": "*" } From 5d6b4e7d119a2ce9d35ef8624a4a5a8e8fb7754b Mon Sep 17 00:00:00 2001 From: Vouchiko Date: Sat, 14 Mar 2026 09:56:39 +0400 Subject: [PATCH 03/10] deleted using --- WarehouseItem.Generator/Service/IWarehouseItemCache.cs | 2 -- WarehouseItem.Generator/Service/IWarehouseItemService.cs | 1 - WarehouseItem.Generator/Service/WarehouseItemCache.cs | 4 ---- 3 files changed, 7 deletions(-) diff --git a/WarehouseItem.Generator/Service/IWarehouseItemCache.cs b/WarehouseItem.Generator/Service/IWarehouseItemCache.cs index 845a9dc1..8013c044 100644 --- a/WarehouseItem.Generator/Service/IWarehouseItemCache.cs +++ b/WarehouseItem.Generator/Service/IWarehouseItemCache.cs @@ -1,5 +1,3 @@ -using System.Threading; -using System.Threading.Tasks; using WarehouseItem.Generator.DTO; namespace WarehouseItem.Generator.Service; diff --git a/WarehouseItem.Generator/Service/IWarehouseItemService.cs b/WarehouseItem.Generator/Service/IWarehouseItemService.cs index 1ca1055f..ea932c49 100644 --- a/WarehouseItem.Generator/Service/IWarehouseItemService.cs +++ b/WarehouseItem.Generator/Service/IWarehouseItemService.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using WarehouseItem.Generator.DTO; namespace WarehouseItem.Generator.Service; diff --git a/WarehouseItem.Generator/Service/WarehouseItemCache.cs b/WarehouseItem.Generator/Service/WarehouseItemCache.cs index fe98b00e..ddf951f1 100644 --- a/WarehouseItem.Generator/Service/WarehouseItemCache.cs +++ b/WarehouseItem.Generator/Service/WarehouseItemCache.cs @@ -1,10 +1,6 @@ using System.Text.Json; using System.Text.Json.Serialization; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Caching.Distributed; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; using WarehouseItem.Generator.DTO; namespace WarehouseItem.Generator.Service; From 81baeb1e49ad4742422b8e6802b3b5839d0ed746 Mon Sep 17 00:00:00 2001 From: Vouchiko Date: Sat, 14 Mar 2026 10:01:02 +0400 Subject: [PATCH 04/10] test --- WarehouseItem.Generator/DTO/WarehouseItemDTO.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs b/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs index dc954c7b..09a8a230 100644 --- a/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs +++ b/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs @@ -54,4 +54,4 @@ public sealed class WarehouseItemDto /// Дата планируемой следующей поставки /// public DateOnly NextDeliveryDate { get; set; } -} +} \ No newline at end of file From 9212048845124eeadb457c0a9dade3be440207ef Mon Sep 17 00:00:00 2001 From: Vouchiko Date: Sat, 14 Mar 2026 10:03:47 +0400 Subject: [PATCH 05/10] rename file --- .../DTO/WarehouseItemDto1.cs | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 WarehouseItem.Generator/DTO/WarehouseItemDto1.cs diff --git a/WarehouseItem.Generator/DTO/WarehouseItemDto1.cs b/WarehouseItem.Generator/DTO/WarehouseItemDto1.cs new file mode 100644 index 00000000..09a8a230 --- /dev/null +++ b/WarehouseItem.Generator/DTO/WarehouseItemDto1.cs @@ -0,0 +1,57 @@ +namespace WarehouseItem.Generator.DTO; + +/// +/// DTO для передачи данных о товаре на складе, включая идентификатор, название, категорию, количество, цену и другие характеристики. +/// +public sealed class WarehouseItemDto +{ + /// + /// Уникальный идентификатор товара + /// + public int Id { get; set; } + + /// + /// Название продукта + /// + public string ProductName { get; set; } = string.Empty; + + /// + /// Категория товара + /// + public string Category { get; set; } = string.Empty; + + /// + /// Количество единиц на складе + /// + public int StockQuantity { get; set; } + + /// + /// Цена за единицу товара + /// + public decimal UnitPrice { get; set; } + + /// + /// Вес одной единицы в килограммах + /// + public double UnitWeight { get; set; } + + /// + /// Размеры одной единицы товара + /// + public string UnitDimensions { get; set; } = string.Empty; + + /// + /// Флаг хрупкого товара + /// + public bool IsFragile { get; set; } + + /// + /// Дата последней поставки + /// + public DateOnly LastDeliveryDate { get; set; } + + /// + /// Дата планируемой следующей поставки + /// + public DateOnly NextDeliveryDate { get; set; } +} \ No newline at end of file From d977691df1e79f187e1c3aadb4064a05b91f9f2c Mon Sep 17 00:00:00 2001 From: Vouchiko Date: Sat, 14 Mar 2026 10:07:32 +0400 Subject: [PATCH 06/10] rename --- .../DTO/WarehouseItemDto12.cs | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 WarehouseItem.Generator/DTO/WarehouseItemDto12.cs diff --git a/WarehouseItem.Generator/DTO/WarehouseItemDto12.cs b/WarehouseItem.Generator/DTO/WarehouseItemDto12.cs new file mode 100644 index 00000000..09a8a230 --- /dev/null +++ b/WarehouseItem.Generator/DTO/WarehouseItemDto12.cs @@ -0,0 +1,57 @@ +namespace WarehouseItem.Generator.DTO; + +/// +/// DTO для передачи данных о товаре на складе, включая идентификатор, название, категорию, количество, цену и другие характеристики. +/// +public sealed class WarehouseItemDto +{ + /// + /// Уникальный идентификатор товара + /// + public int Id { get; set; } + + /// + /// Название продукта + /// + public string ProductName { get; set; } = string.Empty; + + /// + /// Категория товара + /// + public string Category { get; set; } = string.Empty; + + /// + /// Количество единиц на складе + /// + public int StockQuantity { get; set; } + + /// + /// Цена за единицу товара + /// + public decimal UnitPrice { get; set; } + + /// + /// Вес одной единицы в килограммах + /// + public double UnitWeight { get; set; } + + /// + /// Размеры одной единицы товара + /// + public string UnitDimensions { get; set; } = string.Empty; + + /// + /// Флаг хрупкого товара + /// + public bool IsFragile { get; set; } + + /// + /// Дата последней поставки + /// + public DateOnly LastDeliveryDate { get; set; } + + /// + /// Дата планируемой следующей поставки + /// + public DateOnly NextDeliveryDate { get; set; } +} \ No newline at end of file From 0a154dc3370fe8116441c159cbc40f90a685e064 Mon Sep 17 00:00:00 2001 From: Vouchiko Date: Sat, 14 Mar 2026 10:07:41 +0400 Subject: [PATCH 07/10] rename --- .../DTO/WarehouseItemDTO.cs | 57 ------------------- .../DTO/WarehouseItemDto1.cs | 57 ------------------- 2 files changed, 114 deletions(-) delete mode 100644 WarehouseItem.Generator/DTO/WarehouseItemDTO.cs delete mode 100644 WarehouseItem.Generator/DTO/WarehouseItemDto1.cs diff --git a/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs b/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs deleted file mode 100644 index 09a8a230..00000000 --- a/WarehouseItem.Generator/DTO/WarehouseItemDTO.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace WarehouseItem.Generator.DTO; - -/// -/// DTO для передачи данных о товаре на складе, включая идентификатор, название, категорию, количество, цену и другие характеристики. -/// -public sealed class WarehouseItemDto -{ - /// - /// Уникальный идентификатор товара - /// - public int Id { get; set; } - - /// - /// Название продукта - /// - public string ProductName { get; set; } = string.Empty; - - /// - /// Категория товара - /// - public string Category { get; set; } = string.Empty; - - /// - /// Количество единиц на складе - /// - public int StockQuantity { get; set; } - - /// - /// Цена за единицу товара - /// - public decimal UnitPrice { get; set; } - - /// - /// Вес одной единицы в килограммах - /// - public double UnitWeight { get; set; } - - /// - /// Размеры одной единицы товара - /// - public string UnitDimensions { get; set; } = string.Empty; - - /// - /// Флаг хрупкого товара - /// - public bool IsFragile { get; set; } - - /// - /// Дата последней поставки - /// - public DateOnly LastDeliveryDate { get; set; } - - /// - /// Дата планируемой следующей поставки - /// - public DateOnly NextDeliveryDate { get; set; } -} \ No newline at end of file diff --git a/WarehouseItem.Generator/DTO/WarehouseItemDto1.cs b/WarehouseItem.Generator/DTO/WarehouseItemDto1.cs deleted file mode 100644 index 09a8a230..00000000 --- a/WarehouseItem.Generator/DTO/WarehouseItemDto1.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace WarehouseItem.Generator.DTO; - -/// -/// DTO для передачи данных о товаре на складе, включая идентификатор, название, категорию, количество, цену и другие характеристики. -/// -public sealed class WarehouseItemDto -{ - /// - /// Уникальный идентификатор товара - /// - public int Id { get; set; } - - /// - /// Название продукта - /// - public string ProductName { get; set; } = string.Empty; - - /// - /// Категория товара - /// - public string Category { get; set; } = string.Empty; - - /// - /// Количество единиц на складе - /// - public int StockQuantity { get; set; } - - /// - /// Цена за единицу товара - /// - public decimal UnitPrice { get; set; } - - /// - /// Вес одной единицы в килограммах - /// - public double UnitWeight { get; set; } - - /// - /// Размеры одной единицы товара - /// - public string UnitDimensions { get; set; } = string.Empty; - - /// - /// Флаг хрупкого товара - /// - public bool IsFragile { get; set; } - - /// - /// Дата последней поставки - /// - public DateOnly LastDeliveryDate { get; set; } - - /// - /// Дата планируемой следующей поставки - /// - public DateOnly NextDeliveryDate { get; set; } -} \ No newline at end of file From 1fc1a118c290bff497ba493842bfa632ec421aa7 Mon Sep 17 00:00:00 2001 From: Vouchiko Date: Sat, 14 Mar 2026 10:09:14 +0400 Subject: [PATCH 08/10] Final rename --- .../DTO/WarehouseItemDto.cs | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 WarehouseItem.Generator/DTO/WarehouseItemDto.cs diff --git a/WarehouseItem.Generator/DTO/WarehouseItemDto.cs b/WarehouseItem.Generator/DTO/WarehouseItemDto.cs new file mode 100644 index 00000000..09a8a230 --- /dev/null +++ b/WarehouseItem.Generator/DTO/WarehouseItemDto.cs @@ -0,0 +1,57 @@ +namespace WarehouseItem.Generator.DTO; + +/// +/// DTO для передачи данных о товаре на складе, включая идентификатор, название, категорию, количество, цену и другие характеристики. +/// +public sealed class WarehouseItemDto +{ + /// + /// Уникальный идентификатор товара + /// + public int Id { get; set; } + + /// + /// Название продукта + /// + public string ProductName { get; set; } = string.Empty; + + /// + /// Категория товара + /// + public string Category { get; set; } = string.Empty; + + /// + /// Количество единиц на складе + /// + public int StockQuantity { get; set; } + + /// + /// Цена за единицу товара + /// + public decimal UnitPrice { get; set; } + + /// + /// Вес одной единицы в килограммах + /// + public double UnitWeight { get; set; } + + /// + /// Размеры одной единицы товара + /// + public string UnitDimensions { get; set; } = string.Empty; + + /// + /// Флаг хрупкого товара + /// + public bool IsFragile { get; set; } + + /// + /// Дата последней поставки + /// + public DateOnly LastDeliveryDate { get; set; } + + /// + /// Дата планируемой следующей поставки + /// + public DateOnly NextDeliveryDate { get; set; } +} \ No newline at end of file From ff1d1129da4d0d9d18bcd93482e6ebdcfebe8b7b Mon Sep 17 00:00:00 2001 From: Vouchiko Date: Sat, 14 Mar 2026 10:10:18 +0400 Subject: [PATCH 09/10] Final rename --- .../DTO/WarehouseItemDto12.cs | 57 ------------------- 1 file changed, 57 deletions(-) delete mode 100644 WarehouseItem.Generator/DTO/WarehouseItemDto12.cs diff --git a/WarehouseItem.Generator/DTO/WarehouseItemDto12.cs b/WarehouseItem.Generator/DTO/WarehouseItemDto12.cs deleted file mode 100644 index 09a8a230..00000000 --- a/WarehouseItem.Generator/DTO/WarehouseItemDto12.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace WarehouseItem.Generator.DTO; - -/// -/// DTO для передачи данных о товаре на складе, включая идентификатор, название, категорию, количество, цену и другие характеристики. -/// -public sealed class WarehouseItemDto -{ - /// - /// Уникальный идентификатор товара - /// - public int Id { get; set; } - - /// - /// Название продукта - /// - public string ProductName { get; set; } = string.Empty; - - /// - /// Категория товара - /// - public string Category { get; set; } = string.Empty; - - /// - /// Количество единиц на складе - /// - public int StockQuantity { get; set; } - - /// - /// Цена за единицу товара - /// - public decimal UnitPrice { get; set; } - - /// - /// Вес одной единицы в килограммах - /// - public double UnitWeight { get; set; } - - /// - /// Размеры одной единицы товара - /// - public string UnitDimensions { get; set; } = string.Empty; - - /// - /// Флаг хрупкого товара - /// - public bool IsFragile { get; set; } - - /// - /// Дата последней поставки - /// - public DateOnly LastDeliveryDate { get; set; } - - /// - /// Дата планируемой следующей поставки - /// - public DateOnly NextDeliveryDate { get; set; } -} \ No newline at end of file From 925e451febaea06b05e2c3be60a6b56eb9e5039f Mon Sep 17 00:00:00 2001 From: Vouchiko Date: Tue, 14 Apr 2026 10:28:34 +0400 Subject: [PATCH 10/10] Lab 2 --- Client.Wasm/Components/StudentCard.razor | 2 +- Client.Wasm/wwwroot/appsettings.json | 18 ++--- CloudDevelopment.sln | 8 +++ WarehouseItem.AppHost/AppHost.cs | 25 +++++-- .../WarehouseItem.AppHost.csproj | 40 +++++------- .../LoadBalancer/QueryBasedLoadBalancer.cs | 65 +++++++++++++++++++ WarehouseItem.Gateway/Program.cs | 36 ++++++++++ .../WarehouseItem.Gateway.csproj | 17 +++++ WarehouseItem.Gateway/ocelot.json | 20 ++++++ ...ings.json => LaunchSettings.json.disabled} | 0 10 files changed, 194 insertions(+), 37 deletions(-) create mode 100644 WarehouseItem.Gateway/LoadBalancer/QueryBasedLoadBalancer.cs create mode 100644 WarehouseItem.Gateway/Program.cs create mode 100644 WarehouseItem.Gateway/WarehouseItem.Gateway.csproj create mode 100644 WarehouseItem.Gateway/ocelot.json rename WarehouseItem.Generator/Properties/{LaunchSettings.json => LaunchSettings.json.disabled} (100%) diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 5d188b50..9762d5e6 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,7 +4,7 @@ - Номер №1 "Кэширование" + Номер №2 "Балансировка нагрузки" Вариант №23 "Товар на складе" Выполнена Карповым Владимиром 6512 Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index 8a3e0c6c..a425e90a 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -1,10 +1,10 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*", - "BaseAddress": "http://localhost:5204/api/warehouse-item" +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "BaseAddress": "http://localhost:5300/warehouse-item" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index 5eeb6bd3..e3853407 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -11,12 +11,18 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseItem.Generator", " EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseItem.AppHost", "WarehouseItem.AppHost\WarehouseItem.AppHost.csproj", "{07AFB6CB-7359-432D-BF0B-14BA7C582AA5}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseItem.Gateway", "WarehouseItem.Gateway\WarehouseItem.Gateway.csproj", "{D0EFD087-0103-4ACE-AD32-F8A68EDE1988}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D0EFD087-0103-4ACE-AD32-F8A68EDE1988}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D0EFD087-0103-4ACE-AD32-F8A68EDE1988}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D0EFD087-0103-4ACE-AD32-F8A68EDE1988}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D0EFD087-0103-4ACE-AD32-F8A68EDE1988}.Release|Any CPU.Build.0 = Release|Any CPU {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 @@ -41,3 +47,5 @@ Global SolutionGuid = {90FE6B04-8381-437E-893A-FEBA1DA10AEE} EndGlobalSection EndGlobal + + diff --git a/WarehouseItem.AppHost/AppHost.cs b/WarehouseItem.AppHost/AppHost.cs index 77d7c835..c27ad0a0 100644 --- a/WarehouseItem.AppHost/AppHost.cs +++ b/WarehouseItem.AppHost/AppHost.cs @@ -1,13 +1,28 @@ -var builder = DistributedApplication.CreateBuilder(args); +var builder = DistributedApplication.CreateBuilder(args); var cache = builder.AddRedis("warehouse-item-cache") .WithRedisInsight(containerName: "warehouse-item-insight"); -var generator = builder.AddProject("generator") - .WithReference(cache, "warehouse-item-cache") - .WaitFor(cache); +var gateway = builder.AddProject("gateway") + .WithHttpEndpoint(name: "http", port: 5300) + .WithExternalHttpEndpoints(); + +const int generatorPortBase = 5200; +for (var i = 1; i <= 5; ++i) +{ + var generator = builder.AddProject($"generator-{i}") + .WithReference(cache, "warehouse-item-cache") + .WithHttpEndpoint(name: "http", port: generatorPortBase + i) + .WaitFor(cache); + + gateway.WaitFor(generator); +} builder.AddProject("client") - .WaitFor(generator); + .WithReference(gateway) + .WaitFor(gateway); builder.Build().Run(); + + + diff --git a/WarehouseItem.AppHost/WarehouseItem.AppHost.csproj b/WarehouseItem.AppHost/WarehouseItem.AppHost.csproj index 2550d0e2..5cd87dc4 100644 --- a/WarehouseItem.AppHost/WarehouseItem.AppHost.csproj +++ b/WarehouseItem.AppHost/WarehouseItem.AppHost.csproj @@ -1,23 +1,19 @@ - - - - - Exe - net8.0 - enable - enable - ed7e1e47-dc98-4419-8424-85412466aa9b - - - - - - - - - - - - - + + + Exe + net8.0 + enable + enable + ed7e1e47-dc98-4419-8424-85412466aa9b + + + + + + + + + + + \ No newline at end of file diff --git a/WarehouseItem.Gateway/LoadBalancer/QueryBasedLoadBalancer.cs b/WarehouseItem.Gateway/LoadBalancer/QueryBasedLoadBalancer.cs new file mode 100644 index 00000000..876b3cc5 --- /dev/null +++ b/WarehouseItem.Gateway/LoadBalancer/QueryBasedLoadBalancer.cs @@ -0,0 +1,65 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace WarehouseItem.Gateway.LoadBalancer; + +/// +/// Query-based балансировщик нагрузки: выбирает downstream по query-параметру id. +/// Если параметр отсутствует/невалиден — выбирает случайный downstream. +/// +public sealed class QueryBasedLoadBalancer( + ILogger logger, + Func>> servicesProvider) : ILoadBalancer +{ + private const string IdParam = "id"; + + public string Type => nameof(QueryBasedLoadBalancer); + + public void Release(ServiceHostAndPort hostAndPort) { } + + public async Task> LeaseAsync(HttpContext httpContext) + { + var services = await servicesProvider(); + + var selectedIndex = ChooseIndex(httpContext, services.Count, out var parsedId); + + if (parsedId is null) + { + logger.LogWarning("Query param {param} missing/invalid; index={index} selected by random.", IdParam, + selectedIndex); + } + else + { + logger.LogInformation("Query-based selection: id={id} -> index={index}.", parsedId, selectedIndex); + } + + return new OkResponse(services[selectedIndex].HostAndPort); + } + + private static int ChooseIndex(HttpContext httpContext, int servicesCount, out int? id) + { + id = null; + + if (TryParseId(httpContext, out var parsed)) + { + id = parsed; + return parsed % servicesCount; + } + + return Random.Shared.Next(servicesCount); + } + + private static bool TryParseId(HttpContext httpContext, out int id) + { + id = 0; + + if (!httpContext.Request.Query.TryGetValue(IdParam, out var values) || values.Count == 0) + { + return false; + } + + var raw = values[0]; + return !string.IsNullOrWhiteSpace(raw) && int.TryParse(raw, out id) && id >= 0; + } +} diff --git a/WarehouseItem.Gateway/Program.cs b/WarehouseItem.Gateway/Program.cs new file mode 100644 index 00000000..ace626d3 --- /dev/null +++ b/WarehouseItem.Gateway/Program.cs @@ -0,0 +1,36 @@ +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using WarehouseItem.Gateway.LoadBalancer; +using WarehouseItem.ServiceDefaults; + +var builder = WebApplication.CreateBuilder(args); + +const string CorsPolicyName = "LocalDev"; + +builder.AddServiceDefaults(); + +builder.Services.AddCors(static options => +{ + options.AddPolicy(CorsPolicyName, static policy => + policy.AllowAnyOrigin() + .WithHeaders("Content-Type") + .WithMethods("GET")); +}); + +builder.Configuration + .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true) + .AddOcelot(); + +builder.Services + .AddOcelot(builder.Configuration) + .AddCustomLoadBalancer((sp, _, discoveryProvider) => + new QueryBasedLoadBalancer( + sp.GetRequiredService>(), + discoveryProvider.GetAsync)); + +var app = builder.Build(); + +app.UseCors(CorsPolicyName); + +await app.UseOcelot(); +await app.RunAsync(); diff --git a/WarehouseItem.Gateway/WarehouseItem.Gateway.csproj b/WarehouseItem.Gateway/WarehouseItem.Gateway.csproj new file mode 100644 index 00000000..6d24591c --- /dev/null +++ b/WarehouseItem.Gateway/WarehouseItem.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/WarehouseItem.Gateway/ocelot.json b/WarehouseItem.Gateway/ocelot.json new file mode 100644 index 00000000..41d0ba6b --- /dev/null +++ b/WarehouseItem.Gateway/ocelot.json @@ -0,0 +1,20 @@ +{ + "Routes": [ + { + "DownstreamPathTemplate": "/api/warehouse-item", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { "Host": "localhost", "Port": 5201 }, + { "Host": "localhost", "Port": 5202 }, + { "Host": "localhost", "Port": 5203 }, + { "Host": "localhost", "Port": 5204 }, + { "Host": "localhost", "Port": 5205 } + ], + "UpstreamPathTemplate": "/warehouse-item", + "UpstreamHttpMethod": [ "GET" ], + "LoadBalancerOptions": { + "Type": "QueryBasedLoadBalancer" + } + } + ] +} diff --git a/WarehouseItem.Generator/Properties/LaunchSettings.json b/WarehouseItem.Generator/Properties/LaunchSettings.json.disabled similarity index 100% rename from WarehouseItem.Generator/Properties/LaunchSettings.json rename to WarehouseItem.Generator/Properties/LaunchSettings.json.disabled