From 8fd9d9ddcdb4cbafbd94678b1eb33f77616129bd Mon Sep 17 00:00:00 2001 From: Dmitri Date: Fri, 13 Feb 2026 18:27:07 +0400 Subject: [PATCH 01/10] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20=D1=81=D0=B5=D1=80=D0=B2=D0=B8=D1=81=20=D0=B3?= =?UTF-8?q?=D0=B5=D0=BD=D0=B5=D1=80=D0=B0=D1=86=D0=B8=D0=B8=20=D0=B8=20?= =?UTF-8?q?=D0=BA=D1=8D=D1=88=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=BA=D1=80=D0=B5=D0=B4=D0=B8=D1=82=D0=BD=D1=8B=D1=85?= =?UTF-8?q?=20=D0=B7=D0=B0=D1=8F=D0=B2=D0=BE=D0=BA=20=D0=B4=D0=BB=D1=8F=20?= =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B2=D0=BE=D0=B9=20=D0=BB=D0=B0=D0=B1.=20?= =?UTF-8?q?=D1=80=D0=BE=D0=B1=D0=BE=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit В решение добавлены проекты CreditApplication.AppHost (Aspire-хост), CreditApplication.Generator (API генерации кредитных заявок с кэшированием в Redis) и CreditApplication.ServiceDefaults (общие настройки сервисов: логирование, OpenTelemetry, resilience, health checks). Реализована модель заявки, генератор на Bogus, сервис с кэшированием, API-эндпоинт /credit-application. --- Client.Wasm/Components/StudentCard.razor | 8 +- Client.Wasm/Properties/launchSettings.json | 6 +- Client.Wasm/wwwroot/appsettings.json | 4 +- CloudDevelopment.sln | 18 +++ .../CreditApplication.AppHost.csproj | 22 ++++ CreditApplication.AppHost/Program.cs | 13 +++ .../Properties/launchSettings.json | 29 +++++ .../appsettings.Development.json | 9 ++ CreditApplication.AppHost/appsettings.json | 9 ++ .../CreditApplication.Generator.csproj | 18 +++ .../Models/CreditApplicationModel.cs | 57 ++++++++++ CreditApplication.Generator/Program.cs | 59 ++++++++++ .../Properties/launchSettings.json | 23 ++++ .../Services/CreditApplicationGenerator.cs | 96 ++++++++++++++++ .../Services/CreditApplicationService.cs | 60 ++++++++++ .../appsettings.Development.json | 8 ++ CreditApplication.Generator/appsettings.json | 8 ++ .../CreditApplication.ServiceDefaults.csproj | 28 +++++ .../Extensions.cs | 104 ++++++++++++++++++ 19 files changed, 570 insertions(+), 9 deletions(-) create mode 100644 CreditApplication.AppHost/CreditApplication.AppHost.csproj create mode 100644 CreditApplication.AppHost/Program.cs create mode 100644 CreditApplication.AppHost/Properties/launchSettings.json create mode 100644 CreditApplication.AppHost/appsettings.Development.json create mode 100644 CreditApplication.AppHost/appsettings.json create mode 100644 CreditApplication.Generator/CreditApplication.Generator.csproj create mode 100644 CreditApplication.Generator/Models/CreditApplicationModel.cs create mode 100644 CreditApplication.Generator/Program.cs create mode 100644 CreditApplication.Generator/Properties/launchSettings.json create mode 100644 CreditApplication.Generator/Services/CreditApplicationGenerator.cs create mode 100644 CreditApplication.Generator/Services/CreditApplicationService.cs create mode 100644 CreditApplication.Generator/appsettings.Development.json create mode 100644 CreditApplication.Generator/appsettings.json create mode 100644 CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj create mode 100644 CreditApplication.ServiceDefaults/Extensions.cs diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..3dfa61a 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 «Кэширование» + Вариант №4 «Кредитная заявка» + Выполнена Горшениным Дмитрием 6511 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea..5e0be66 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -1,4 +1,4 @@ -{ +{ "$schema": "http://json.schemastore.org/launchsettings.json", "iisSettings": { "windowsAuthentication": false, @@ -14,7 +14,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", - "applicationUrl": "http://localhost:5127", + "applicationUrl": "http://localhost:5128", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -24,7 +24,7 @@ "dotnetRunMessages": true, "launchBrowser": true, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", - "applicationUrl": "https://localhost:7282;http://localhost:5127", + "applicationUrl": "https://localhost:7283;http://localhost:5128", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index 4dda7c0..463eb0e 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": "https://localhost:7170/land-plot" + "BaseAddress": "https://localhost:7171/credit-application" } \ No newline at end of file diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241..0ce0c90 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}") = "CreditApplication.AppHost", "CreditApplication.AppHost\CreditApplication.AppHost.csproj", "{8D7BA58C-B453-616F-C170-8D20E1B277D5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApplication.Generator", "CreditApplication.Generator\CreditApplication.Generator.csproj", "{795D187F-BDDB-12D5-574B-DB27A6FAA1B2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApplication.ServiceDefaults", "CreditApplication.ServiceDefaults\CreditApplication.ServiceDefaults.csproj", "{3E99472D-C53C-A52E-DCDC-C663DE0B4459}" +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 + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Release|Any CPU.Build.0 = Release|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Release|Any CPU.Build.0 = Release|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CreditApplication.AppHost/CreditApplication.AppHost.csproj b/CreditApplication.AppHost/CreditApplication.AppHost.csproj new file mode 100644 index 0000000..a80e9f7 --- /dev/null +++ b/CreditApplication.AppHost/CreditApplication.AppHost.csproj @@ -0,0 +1,22 @@ + + + + Exe + net8.0 + enable + enable + true + + + + + + + + + + + + + + diff --git a/CreditApplication.AppHost/Program.cs b/CreditApplication.AppHost/Program.cs new file mode 100644 index 0000000..260ea2c --- /dev/null +++ b/CreditApplication.AppHost/Program.cs @@ -0,0 +1,13 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisCommander(); + +var generator = builder.AddProject("generator") + .WithReference(redis) + .WithExternalHttpEndpoints(); + +builder.AddProject("client") + .WithReference(generator); + +builder.Build().Run(); diff --git a/CreditApplication.AppHost/Properties/launchSettings.json b/CreditApplication.AppHost/Properties/launchSettings.json new file mode 100644 index 0000000..c2e8028 --- /dev/null +++ b/CreditApplication.AppHost/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17170;http://localhost:15170", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21170", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22170" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15170", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19170", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20170" + } + } + } +} diff --git a/CreditApplication.AppHost/appsettings.Development.json b/CreditApplication.AppHost/appsettings.Development.json new file mode 100644 index 0000000..bfad985 --- /dev/null +++ b/CreditApplication.AppHost/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CreditApplication.AppHost/appsettings.json b/CreditApplication.AppHost/appsettings.json new file mode 100644 index 0000000..bfad985 --- /dev/null +++ b/CreditApplication.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CreditApplication.Generator/CreditApplication.Generator.csproj b/CreditApplication.Generator/CreditApplication.Generator.csproj new file mode 100644 index 0000000..bbba1ad --- /dev/null +++ b/CreditApplication.Generator/CreditApplication.Generator.csproj @@ -0,0 +1,18 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + diff --git a/CreditApplication.Generator/Models/CreditApplicationModel.cs b/CreditApplication.Generator/Models/CreditApplicationModel.cs new file mode 100644 index 0000000..5ee266d --- /dev/null +++ b/CreditApplication.Generator/Models/CreditApplicationModel.cs @@ -0,0 +1,57 @@ +namespace CreditApplication.Generator.Models; + +/// +/// Модель кредитной заявки +/// +public class CreditApplicationModel +{ + /// + /// Идентификатор в системе + /// + public int Id { get; set; } + + /// + /// Тип кредита (Потребительский, Ипотека, Автокредит и т.д.) + /// + public string CreditType { get; set; } = string.Empty; + + /// + /// Запрашиваемая сумма (округляется до 2 знаков) + /// + public decimal RequestedAmount { get; set; } + + /// + /// Срок в месяцах + /// + public int TermInMonths { get; set; } + + /// + /// Процентная ставка (не менее ставки ЦБ РФ, округляется до 2 знаков) + /// + public double InterestRate { get; set; } + + /// + /// Дата подачи (не более 2 лет назад) + /// + public DateOnly ApplicationDate { get; set; } + + /// + /// Необходимость страховки + /// + public bool InsuranceRequired { get; set; } + + /// + /// Статус заявки (Новая, В обработке, Одобрена, Отклонена) + /// + public string Status { get; set; } = string.Empty; + + /// + /// Дата решения (только для терминальных статусов) + /// + public DateOnly? DecisionDate { get; set; } + + /// + /// Одобренная сумма (только для статуса "Одобрена", <= RequestedAmount) + /// + public decimal? ApprovedAmount { get; set; } +} diff --git a/CreditApplication.Generator/Program.cs b/CreditApplication.Generator/Program.cs new file mode 100644 index 0000000..44c9544 --- /dev/null +++ b/CreditApplication.Generator/Program.cs @@ -0,0 +1,59 @@ +using CreditApplication.Generator.Services; +using CreditApplication.ServiceDefaults; +using Serilog; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddSingleton(); +builder.Services.AddScoped(); + +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + { + policy.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + }); +}); + +var app = builder.Build(); + +app.UseCors(); +app.UseSerilogRequestLogging(); + +app.MapDefaultEndpoints(); + +// API endpoint для получения кредитной заявки +app.MapGet("/credit-application", async ( + int id, + CreditApplicationService service, + ILogger logger, + CancellationToken cancellationToken) => +{ + logger.LogInformation("Received request for credit application with ID: {Id}", id); + + if (id <= 0) + { + logger.LogWarning("Received invalid ID: {Id}", id); + return Results.BadRequest(new { error = "ID must be a positive number" }); + } + + try + { + var application = await service.GetByIdAsync(id, cancellationToken); + return Results.Ok(application); + } + catch (Exception ex) + { + logger.LogError(ex, "Error while getting credit application {Id}", id); + return Results.Problem("An error occurred while processing the request"); + } +}) +.WithName("GetCreditApplication"); + +app.Run(); diff --git a/CreditApplication.Generator/Properties/launchSettings.json b/CreditApplication.Generator/Properties/launchSettings.json new file mode 100644 index 0000000..ea1476c --- /dev/null +++ b/CreditApplication.Generator/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5171", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7171;http://localhost:5171", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CreditApplication.Generator/Services/CreditApplicationGenerator.cs b/CreditApplication.Generator/Services/CreditApplicationGenerator.cs new file mode 100644 index 0000000..e6ef408 --- /dev/null +++ b/CreditApplication.Generator/Services/CreditApplicationGenerator.cs @@ -0,0 +1,96 @@ +using Bogus; +using CreditApplication.Generator.Models; + +namespace CreditApplication.Generator.Services; + +/// +/// Генератор кредитных заявок на основе Bogus +/// +public class CreditApplicationGenerator(ILogger logger) +{ + private const double MinInterestRate = 16.0; + + private static readonly string[] _creditTypes = + [ + "Потребительский", + "Ипотека", + "Автокредит", + "Кредит на образование", + "Кредит на рефинансирование" + ]; + + private static readonly string[] _statuses = + [ + "Новая", + "В обработке", + "Одобрена", + "Отклонена" + ]; + + private static readonly string[] _terminalStatuses = ["Одобрена", "Отклонена"]; + + private readonly ILogger _logger = logger; + + /// + /// Генерирует кредитную заявку по указанному идентификатору + /// + /// Идентификатор заявки (используется как seed для повторяемости) + /// Сгенерированная кредитная заявка + public CreditApplicationModel Generate(int id) + { + _logger.LogInformation("Generating credit application with ID: {Id}", id); + + var faker = new Faker("ru") + .UseSeed(id) + .RuleFor(x => x.Id, _ => id) + .RuleFor(x => x.CreditType, f => f.PickRandom(_creditTypes)) + .RuleFor(x => x.RequestedAmount, f => Math.Round(f.Random.Decimal(50_000m, 10_000_000m), 2)) + .RuleFor(x => x.TermInMonths, f => f.Random.Int(6, 360)) + .RuleFor(x => x.InterestRate, f => Math.Round(f.Random.Double(MinInterestRate, 35.0), 2)) + .RuleFor(x => x.ApplicationDate, f => GenerateApplicationDate(f)) + .RuleFor(x => x.InsuranceRequired, f => f.Random.Bool()) + .RuleFor(x => x.Status, f => f.PickRandom(_statuses)) + .FinishWith((f, app) => + { + SetStatusDependentFields(f, app); + }); + + var application = faker.Generate(); + + _logger.LogInformation( + "Credit application generated: ID={Id}, Type={CreditType}, Status={Status}, Amount={Amount}", + application.Id, + application.CreditType, + application.Status, + application.RequestedAmount); + + return application; + } + + private static DateOnly GenerateApplicationDate(Faker faker) + { + var minDate = DateTime.Today.AddYears(-2); + var maxDate = DateTime.Today; + var randomDate = faker.Date.Between(minDate, maxDate); + return DateOnly.FromDateTime(randomDate); + } + + private static void SetStatusDependentFields(Faker faker, CreditApplicationModel app) + { + var isTerminal = _terminalStatuses.Contains(app.Status); + + if (isTerminal) + { + var applicationDateTime = app.ApplicationDate.ToDateTime(TimeOnly.MinValue); + var decisionDateTime = faker.Date.Between(applicationDateTime, DateTime.Today); + app.DecisionDate = DateOnly.FromDateTime(decisionDateTime); + + if (app.Status == "Одобрена") + { + var maxApproved = app.RequestedAmount; + var minApproved = maxApproved * 0.5m; + app.ApprovedAmount = Math.Round(faker.Random.Decimal(minApproved, maxApproved), 2); + } + } + } +} diff --git a/CreditApplication.Generator/Services/CreditApplicationService.cs b/CreditApplication.Generator/Services/CreditApplicationService.cs new file mode 100644 index 0000000..974f607 --- /dev/null +++ b/CreditApplication.Generator/Services/CreditApplicationService.cs @@ -0,0 +1,60 @@ +using System.Text.Json; +using CreditApplication.Generator.Models; +using Microsoft.Extensions.Caching.Distributed; + +namespace CreditApplication.Generator.Services; + +/// +/// Сервис кредитных заявок с поддержкой кэширования +/// +public class CreditApplicationService( + CreditApplicationGenerator generator, + IDistributedCache cache, + ILogger logger) +{ + private readonly CreditApplicationGenerator _generator = generator; + private readonly IDistributedCache _cache = cache; + private readonly ILogger _logger = logger; + + private static readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes(5); + private const string CacheKeyPrefix = "credit-application:"; + + /// + /// Получает кредитную заявку по ID. + /// При первом запросе генерирует и кэширует, при повторном - возвращает из кэша. + /// + public async Task GetByIdAsync(int id, CancellationToken cancellationToken = default) + { + var cacheKey = $"{CacheKeyPrefix}{id}"; + + _logger.LogInformation("Request for credit application with ID: {Id}", id); + + var cachedData = await _cache.GetStringAsync(cacheKey, cancellationToken); + + if (!string.IsNullOrEmpty(cachedData)) + { + _logger.LogInformation("Credit application {Id} found in cache", id); + var cachedApplication = JsonSerializer.Deserialize(cachedData); + return cachedApplication!; + } + + _logger.LogInformation("Credit application {Id} not found in cache, generating new one", id); + + var application = _generator.Generate(id); + + var serializedData = JsonSerializer.Serialize(application); + var cacheOptions = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheExpiration + }; + + await _cache.SetStringAsync(cacheKey, serializedData, cacheOptions, cancellationToken); + + _logger.LogInformation( + "Credit application {Id} saved to cache with TTL {CacheExpiration} minutes", + id, + _cacheExpiration.TotalMinutes); + + return application; + } +} diff --git a/CreditApplication.Generator/appsettings.Development.json b/CreditApplication.Generator/appsettings.Development.json new file mode 100644 index 0000000..b0bacf4 --- /dev/null +++ b/CreditApplication.Generator/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CreditApplication.Generator/appsettings.json b/CreditApplication.Generator/appsettings.json new file mode 100644 index 0000000..b0bacf4 --- /dev/null +++ b/CreditApplication.Generator/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj b/CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj new file mode 100644 index 0000000..7ad1878 --- /dev/null +++ b/CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj @@ -0,0 +1,28 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + + + + + + + diff --git a/CreditApplication.ServiceDefaults/Extensions.cs b/CreditApplication.ServiceDefaults/Extensions.cs new file mode 100644 index 0000000..d38113f --- /dev/null +++ b/CreditApplication.ServiceDefaults/Extensions.cs @@ -0,0 +1,104 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; +using Serilog; + +namespace CreditApplication.ServiceDefaults; + +public static class Extensions +{ + public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder) + { + builder.ConfigureSerilog(); + builder.ConfigureOpenTelemetry(); + builder.AddDefaultHealthChecks(); + builder.Services.AddServiceDiscovery(); + builder.Services.ConfigureHttpClientDefaults(http => + { + http.AddStandardResilienceHandler(); + http.AddServiceDiscovery(); + }); + + return builder; + } + + public static IHostApplicationBuilder ConfigureSerilog(this IHostApplicationBuilder builder) + { + Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(builder.Configuration) + .Enrich.FromLogContext() + .Enrich.WithEnvironmentName() + .Enrich.WithThreadId() + .Enrich.WithMachineName() + .WriteTo.Console(outputTemplate: + "[{Timestamp:HH:mm:ss} {Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}") + .CreateLogger(); + + builder.Services.AddSerilog(); + + return builder; + } + + public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder) + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static IHostApplicationBuilder AddOpenTelemetryExporters(this IHostApplicationBuilder builder) + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + return builder; + } + + public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicationBuilder builder) + { + builder.Services.AddHealthChecks() + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + app.MapHealthChecks("/health"); + app.MapHealthChecks("/alive", new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + + return app; + } +} From e1db504bf4b2ae218151a86abbc4094bda7594e3 Mon Sep 17 00:00:00 2001 From: dmgorshenin <113519315+dmgorshenin@users.noreply.github.com> Date: Fri, 13 Feb 2026 18:48:40 +0400 Subject: [PATCH 02/10] Update README.md --- README.md | 197 +++++++++++++++++++----------------------------------- 1 file changed, 70 insertions(+), 127 deletions(-) diff --git a/README.md b/README.md index dcaa5eb..9e29c51 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,71 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing) - -## Задание -### Цель -Реализация проекта микросервисного бекенда. - -### Задачи -* Реализация межсервисной коммуникации, -* Изучение работы с брокерами сообщений, -* Изучение архитектурных паттернов, -* Изучение работы со средствами оркестрации на примере .NET Aspire, -* Повторение основ работы с системами контроля версий, -* Интеграционное тестирование. - -### Лабораторные работы -
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов -
- -В рамках первой лабораторной работы необходимо: -* Реализовать сервис генерации контрактов на основе Bogus, -* Реализовать кеширование при помощи IDistributedCache и Redis, -* Реализовать структурное логирование сервиса генерации, -* Настроить оркестрацию Aspire. - -
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы -
- -В рамках второй лабораторной работы необходимо: -* Настроить оркестрацию на запуск нескольких реплик сервиса генерации, -* Реализовать апи гейтвей на основе Ocelot, -* Имплементировать алгоритм балансировки нагрузки согласно варианту. - -
-
-
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда -
- -В рамках третьей лабораторной работы необходимо: -* Добавить в оркестрацию объектное хранилище, -* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище, -* Реализовать отправку генерируемых данных в файловый сервис посредством брокера, -* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе. - -
-
-
-4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud -
- -В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы: -* Клиент - в хостинг через отдельный бакет Object Storage, -* Сервис генерации - в Cloud Function, -* Апи гейтвей - в Serverless Integration как API Gateway, -* Брокер сообщений - в Message Queue, -* Файловый сервис - в Cloud Function, -* Объектное хранилище - в отдельный бакет Object Storage, - -
-
- -## Задание. Общая часть -**Обязательно**: -* Реализация серверной части на [.NET 8](https://learn.microsoft.com/ru-ru/dotnet/core/whats-new/dotnet-8/overview). -* Оркестрация проектов при помощи [.NET Aspire](https://learn.microsoft.com/ru-ru/dotnet/aspire/get-started/aspire-overview). -* Реализация сервиса генерации данных при помощи [Bogus](https://github.com/bchavez/Bogus). -* Реализация тестов с использованием [xUnit](https://xunit.net/?tabs=cs). -* Создание минимальной документации к проекту: страница на GitHub с информацией о задании, скриншоты приложения и прочая информация. - -**Факультативно**: -* Перенос бекенда на облачную инфраструктуру Yandex Cloud - -Внимательно прочитайте [дискуссии](https://github.com/itsecd/cloud-development/discussions/1) о том, как работает автоматическое распределение на ревью. -Сразу корректно называйте свои pr, чтобы они попали на ревью нужному преподавателю. - -По итогу работы в семестре должна получиться следующая информационная система: -
-C4 диаграмма -Современные_технологии_разработки_ПО_drawio -
- -## Варианты заданий -Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи. - -[Список вариантов](https://docs.google.com/document/d/1WGmLYwffTTaAj4TgFCk5bUyW3XKbFMiBm-DHZrfFWr4/edit?usp=sharing) -[Список предметных областей и алгоритмов балансировки](https://docs.google.com/document/d/1PLn2lKe4swIdJDZhwBYzxqFSu0AbY2MFY1SUPkIKOM4/edit?usp=sharing) - -## Схема сдачи - -На каждую из лабораторных работ необходимо сделать отдельный [Pull Request (PR)](https://docs.github.com/en/pull-requests). - -Общая схема: -1. Сделать форк данного репозитория -2. Выполнить задание -3. Сделать PR в данный репозиторий -4. Исправить замечания после code review -5. Получить approve - -## Критерии оценивания - -Конкурентный принцип. -Так как задания в первой лабораторной будут повторяться между студентами, то выделяются следующие показатели для оценки: -1. Скорость разработки -2. Качество разработки -3. Полнота выполнения задания - -Быстрее делаете PR - у вас преимущество. -Быстрее получаете Approve - у вас преимущество. -Выполните нечто немного выходящее за рамки проекта - у вас преимущество. -Не укладываетесь в дедлайн - получаете минимально возможный балл. - -### Шкала оценивания - -- **3 балла** за качество кода, из них: - - 2 балла - базовая оценка - - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов: - - Реализация факультативного функционала - - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл - -## Вопросы и обратная связь по курсу - -Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](https://github.com/itsecd/cloud-development/discussions/categories/questions) или заведите [ишью](https://github.com/itsecd/cloud-development/issues/new). -Если у вас появились идеи/пожелания/прочие полезные мысли по преподаваемой дисциплине, их можно оставить [здесь](https://github.com/itsecd/cloud-development/discussions/categories/ideas). +# Генератор "Кредитной заявки" - Лабораторная #1 "Кэширование" + +> **Лабораторная работа #1** | **Вариант #4** "Кредитная заявка" +> **Студент:** Дмитрий Горшенин, группа 6511 +> **Репозиторий:** [github.com/dmgorshenin/cloud-development](https://github.com/dmgorshenin/cloud-development) + +## 📝 Описание задачи + +Реализация микросервиса для генерации заявок на кредит с поддержкой кэширования с использованием оркестровки .NET Aspire. + +### Цели +- Реализация сервиса генерации контрактов на основе Bogus +- Реализация кэширования с использованием IDistributedCache и Redis +- Реализация структурированного логирования для сервиса генерации +- Настройка оркестрации Aspire + +### Детали варианта +**Вариант №4 - Кредитная заявка** + +Сервис генерирует данные заявки на кредит со следующими характеристиками: +- Типы кредитов: Потребительский кредит, Ипотека, Автокредит, Образовательный кредит, Кредит на рефинансирование +- Процентные ставки: минимум 16% (ставка ЦБ РФ на момент создания лабораторной) +- Статусы заявки: Новая, В процессе, Одобрена, Отклонена +- Автоматический расчет сумм одобрения и дат принятия решения на основе статуса + + +## 🏗️ Архитектура + +Решение состоит из следующих проектов: + +``` +cloud-development/ +├── CreditApplication.Generator/ # Сервис генерации заявок на кредит +│ ├── Services/ +│ │ ├── CreditApplicationGenerator.cs # Генератор на основе некорректных данных +│ │ └── CreditApplicationService.cs # Сервис с кэшированием +│ └── Models/ +│ └── CreditApplicationModel.cs # Модель данных кредитной заявки +├── CreditApplication.AppHost/ # Оркестрация .NET Aspire +├── CreditApplication.ServiceDefaults/ # Конфигурации общих сервисов (Serilog, OpenTelemetry) +└── Client.Wasm/ # Клиент Blazor WebAssembly + └── Components/ + ├── DataCard.razor # Просмотрщик кредитных заявок + └── StudentCard.razor # Отображение информации о лаборатории +``` + +### Архитектурная диаграмма + +```mermaid +graph TB + Client[Blazor WebAssembly Client] + Generator[Credit Application Generator Service] + Redis[(Redis Cache)] + + Client -->|HTTP Request| Generator + Generator -->|Cache Check| Redis + Redis -->|Cached Data| Generator + Generator -->|Generate New| Bogus[Bogus Faker] + Generator -->|Save to Cache| Redis + Generator -->|Response| Client +``` + +### Скриншоты +image +image +image +image + + + From c0518fa78b6e178c654e682f647ab899271ba4ea Mon Sep 17 00:00:00 2001 From: Dmitri Date: Fri, 13 Feb 2026 18:50:02 +0400 Subject: [PATCH 03/10] =?UTF-8?q?=D0=9E=D1=87=D0=B8=D1=81=D1=82=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=BA=D0=BE=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CreditApplication.Generator/Program.cs | 4 ++-- .../Services/CreditApplicationGenerator.cs | 10 +++++----- .../Services/CreditApplicationService.cs | 16 ++++++++-------- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/CreditApplication.Generator/Program.cs b/CreditApplication.Generator/Program.cs index 44c9544..4211af1 100644 --- a/CreditApplication.Generator/Program.cs +++ b/CreditApplication.Generator/Program.cs @@ -36,13 +36,13 @@ CancellationToken cancellationToken) => { logger.LogInformation("Received request for credit application with ID: {Id}", id); - + if (id <= 0) { logger.LogWarning("Received invalid ID: {Id}", id); return Results.BadRequest(new { error = "ID must be a positive number" }); } - + try { var application = await service.GetByIdAsync(id, cancellationToken); diff --git a/CreditApplication.Generator/Services/CreditApplicationGenerator.cs b/CreditApplication.Generator/Services/CreditApplicationGenerator.cs index e6ef408..06c1e2a 100644 --- a/CreditApplication.Generator/Services/CreditApplicationGenerator.cs +++ b/CreditApplication.Generator/Services/CreditApplicationGenerator.cs @@ -9,8 +9,8 @@ namespace CreditApplication.Generator.Services; public class CreditApplicationGenerator(ILogger logger) { private const double MinInterestRate = 16.0; - - private static readonly string[] _creditTypes = + + private static readonly string[] _creditTypes = [ "Потребительский", "Ипотека", @@ -19,7 +19,7 @@ public class CreditApplicationGenerator(ILogger logg "Кредит на рефинансирование" ]; - private static readonly string[] _statuses = + private static readonly string[] _statuses = [ "Новая", "В обработке", @@ -56,7 +56,7 @@ public CreditApplicationModel Generate(int id) }); var application = faker.Generate(); - + _logger.LogInformation( "Credit application generated: ID={Id}, Type={CreditType}, Status={Status}, Amount={Amount}", application.Id, @@ -78,7 +78,7 @@ private static DateOnly GenerateApplicationDate(Faker faker) private static void SetStatusDependentFields(Faker faker, CreditApplicationModel app) { var isTerminal = _terminalStatuses.Contains(app.Status); - + if (isTerminal) { var applicationDateTime = app.ApplicationDate.ToDateTime(TimeOnly.MinValue); diff --git a/CreditApplication.Generator/Services/CreditApplicationService.cs b/CreditApplication.Generator/Services/CreditApplicationService.cs index 974f607..423d9b2 100644 --- a/CreditApplication.Generator/Services/CreditApplicationService.cs +++ b/CreditApplication.Generator/Services/CreditApplicationService.cs @@ -1,6 +1,6 @@ -using System.Text.Json; -using CreditApplication.Generator.Models; +using CreditApplication.Generator.Models; using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; namespace CreditApplication.Generator.Services; @@ -15,7 +15,7 @@ public class CreditApplicationService( private readonly CreditApplicationGenerator _generator = generator; private readonly IDistributedCache _cache = cache; private readonly ILogger _logger = logger; - + private static readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes(5); private const string CacheKeyPrefix = "credit-application:"; @@ -26,11 +26,11 @@ public class CreditApplicationService( public async Task GetByIdAsync(int id, CancellationToken cancellationToken = default) { var cacheKey = $"{CacheKeyPrefix}{id}"; - + _logger.LogInformation("Request for credit application with ID: {Id}", id); var cachedData = await _cache.GetStringAsync(cacheKey, cancellationToken); - + if (!string.IsNullOrEmpty(cachedData)) { _logger.LogInformation("Credit application {Id} found in cache", id); @@ -39,7 +39,7 @@ public async Task GetByIdAsync(int id, CancellationToken } _logger.LogInformation("Credit application {Id} not found in cache, generating new one", id); - + var application = _generator.Generate(id); var serializedData = JsonSerializer.Serialize(application); @@ -47,9 +47,9 @@ public async Task GetByIdAsync(int id, CancellationToken { AbsoluteExpirationRelativeToNow = _cacheExpiration }; - + await _cache.SetStringAsync(cacheKey, serializedData, cacheOptions, cancellationToken); - + _logger.LogInformation( "Credit application {Id} saved to cache with TTL {CacheExpiration} minutes", id, From 90ecc6efed12807268ec19fcff15111ae8e44848 Mon Sep 17 00:00:00 2001 From: dmgorshenin <113519315+dmgorshenin@users.noreply.github.com> Date: Fri, 13 Feb 2026 18:51:09 +0400 Subject: [PATCH 04/10] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9e29c51..18e929c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# Генератор "Кредитной заявки" - Лабораторная #1 "Кэширование" +# Генератор "Кредитной заявки" -> **Лабораторная работа #1** | **Вариант #4** "Кредитная заявка" +> **Вариант #4** "Кредитная заявка" > **Студент:** Дмитрий Горшенин, группа 6511 > **Репозиторий:** [github.com/dmgorshenin/cloud-development](https://github.com/dmgorshenin/cloud-development) From 8d9edeaa604963be689c8740caa2f6c79a66462e Mon Sep 17 00:00:00 2001 From: dmgorshenin <113519315+dmgorshenin@users.noreply.github.com> Date: Fri, 13 Feb 2026 23:47:43 +0400 Subject: [PATCH 05/10] Update README.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 18e929c..b0e71fc 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ cloud-development/ ├── CreditApplication.Generator/ # Сервис генерации заявок на кредит │ ├── Services/ -│ │ ├── CreditApplicationGenerator.cs # Генератор на основе некорректных данных +│ │ ├── CreditApplicationGenerator.cs # Генератор на основе Bogus │ │ └── CreditApplicationService.cs # Сервис с кэшированием │ └── Models/ │ └── CreditApplicationModel.cs # Модель данных кредитной заявки From 85e73d250ce0da92ea120881b45c5a5b0292358b Mon Sep 17 00:00:00 2001 From: Dmitri Date: Mon, 16 Feb 2026 15:41:15 +0400 Subject: [PATCH 06/10] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Client.Wasm/Properties/launchSettings.json | 6 ++--- .../CreditApplication.AppHost.csproj | 10 ++++--- .../CreditApplication.Generator.csproj | 2 +- CreditApplication.Generator/Program.cs | 15 ++++++++--- .../Services/CreditApplicationGenerator.cs | 27 +++++-------------- .../Services/CreditApplicationService.cs | 14 +++++++--- CreditApplication.Generator/appsettings.json | 3 +++ .../CreditApplication.ServiceDefaults.csproj | 2 +- README.md | 2 +- 9 files changed, 44 insertions(+), 37 deletions(-) diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 5e0be66..1842f72 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -12,7 +12,7 @@ "http": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "http://localhost:5128", "environmentVariables": { @@ -22,7 +22,7 @@ "https": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "https://localhost:7283;http://localhost:5128", "environmentVariables": { @@ -31,7 +31,7 @@ }, "IIS Express": { "commandName": "IISExpress", - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" diff --git a/CreditApplication.AppHost/CreditApplication.AppHost.csproj b/CreditApplication.AppHost/CreditApplication.AppHost.csproj index a80e9f7..ad13098 100644 --- a/CreditApplication.AppHost/CreditApplication.AppHost.csproj +++ b/CreditApplication.AppHost/CreditApplication.AppHost.csproj @@ -1,6 +1,8 @@  - + + + Exe net8.0 enable @@ -9,9 +11,9 @@ - - - + + + diff --git a/CreditApplication.Generator/CreditApplication.Generator.csproj b/CreditApplication.Generator/CreditApplication.Generator.csproj index bbba1ad..e4096cb 100644 --- a/CreditApplication.Generator/CreditApplication.Generator.csproj +++ b/CreditApplication.Generator/CreditApplication.Generator.csproj @@ -7,7 +7,7 @@ - + diff --git a/CreditApplication.Generator/Program.cs b/CreditApplication.Generator/Program.cs index 4211af1..bc3a7b3 100644 --- a/CreditApplication.Generator/Program.cs +++ b/CreditApplication.Generator/Program.cs @@ -15,9 +15,18 @@ { options.AddDefaultPolicy(policy => { - policy.AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader(); + if (builder.Environment.IsDevelopment()) + { + policy.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + } + else + { + policy.WithOrigins("https://your-production-frontend.example") + .WithMethods("GET") + .WithHeaders("Content-Type", "Authorization"); + } }); }); diff --git a/CreditApplication.Generator/Services/CreditApplicationGenerator.cs b/CreditApplication.Generator/Services/CreditApplicationGenerator.cs index 06c1e2a..9075ca0 100644 --- a/CreditApplication.Generator/Services/CreditApplicationGenerator.cs +++ b/CreditApplication.Generator/Services/CreditApplicationGenerator.cs @@ -29,8 +29,6 @@ public class CreditApplicationGenerator(ILogger logg private static readonly string[] _terminalStatuses = ["Одобрена", "Отклонена"]; - private readonly ILogger _logger = logger; - /// /// Генерирует кредитную заявку по указанному идентификатору /// @@ -38,7 +36,7 @@ public class CreditApplicationGenerator(ILogger logg /// Сгенерированная кредитная заявка public CreditApplicationModel Generate(int id) { - _logger.LogInformation("Generating credit application with ID: {Id}", id); + logger.LogInformation("Generating credit application with ID: {Id}", id); var faker = new Faker("ru") .UseSeed(id) @@ -47,17 +45,14 @@ public CreditApplicationModel Generate(int id) .RuleFor(x => x.RequestedAmount, f => Math.Round(f.Random.Decimal(50_000m, 10_000_000m), 2)) .RuleFor(x => x.TermInMonths, f => f.Random.Int(6, 360)) .RuleFor(x => x.InterestRate, f => Math.Round(f.Random.Double(MinInterestRate, 35.0), 2)) - .RuleFor(x => x.ApplicationDate, f => GenerateApplicationDate(f)) + .RuleFor(x => x.ApplicationDate, f => f.Date.PastDateOnly(2)) .RuleFor(x => x.InsuranceRequired, f => f.Random.Bool()) .RuleFor(x => x.Status, f => f.PickRandom(_statuses)) - .FinishWith((f, app) => - { - SetStatusDependentFields(f, app); - }); + .FinishWith(SetStatusDependentFields); var application = faker.Generate(); - - _logger.LogInformation( + + logger.LogInformation( "Credit application generated: ID={Id}, Type={CreditType}, Status={Status}, Amount={Amount}", application.Id, application.CreditType, @@ -67,23 +62,13 @@ public CreditApplicationModel Generate(int id) return application; } - private static DateOnly GenerateApplicationDate(Faker faker) - { - var minDate = DateTime.Today.AddYears(-2); - var maxDate = DateTime.Today; - var randomDate = faker.Date.Between(minDate, maxDate); - return DateOnly.FromDateTime(randomDate); - } - private static void SetStatusDependentFields(Faker faker, CreditApplicationModel app) { var isTerminal = _terminalStatuses.Contains(app.Status); if (isTerminal) { - var applicationDateTime = app.ApplicationDate.ToDateTime(TimeOnly.MinValue); - var decisionDateTime = faker.Date.Between(applicationDateTime, DateTime.Today); - app.DecisionDate = DateOnly.FromDateTime(decisionDateTime); + app.DecisionDate = faker.Date.BetweenDateOnly(app.ApplicationDate, DateOnly.FromDateTime(DateTime.Today)); if (app.Status == "Одобрена") { diff --git a/CreditApplication.Generator/Services/CreditApplicationService.cs b/CreditApplication.Generator/Services/CreditApplicationService.cs index 423d9b2..fcf41bd 100644 --- a/CreditApplication.Generator/Services/CreditApplicationService.cs +++ b/CreditApplication.Generator/Services/CreditApplicationService.cs @@ -10,13 +10,15 @@ namespace CreditApplication.Generator.Services; public class CreditApplicationService( CreditApplicationGenerator generator, IDistributedCache cache, + IConfiguration configuration, ILogger logger) { private readonly CreditApplicationGenerator _generator = generator; private readonly IDistributedCache _cache = cache; private readonly ILogger _logger = logger; - - private static readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes(5); + + private readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes( + configuration.GetValue("CacheSettings:ExpirationMinutes", 5)); private const string CacheKeyPrefix = "credit-application:"; /// @@ -35,7 +37,13 @@ public async Task GetByIdAsync(int id, CancellationToken { _logger.LogInformation("Credit application {Id} found in cache", id); var cachedApplication = JsonSerializer.Deserialize(cachedData); - return cachedApplication!; + + if (cachedApplication is not null) + { + return cachedApplication; + } + + _logger.LogWarning("Cached data for credit application {Id} deserialized to null, regenerating", id); } _logger.LogInformation("Credit application {Id} not found in cache, generating new one", id); diff --git a/CreditApplication.Generator/appsettings.json b/CreditApplication.Generator/appsettings.json index b0bacf4..a9ceb83 100644 --- a/CreditApplication.Generator/appsettings.json +++ b/CreditApplication.Generator/appsettings.json @@ -4,5 +4,8 @@ "Default": "Information", "Microsoft.AspNetCore": "Warning" } + }, + "CacheSettings": { + "ExpirationMinutes": 5 } } diff --git a/CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj b/CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj index 7ad1878..7cd1cfd 100644 --- a/CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj +++ b/CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj @@ -13,7 +13,7 @@ - + diff --git a/README.md b/README.md index 18e929c..9919620 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Генератор "Кредитной заявки" +# Генератор "Кредитной заявки" > **Вариант #4** "Кредитная заявка" > **Студент:** Дмитрий Горшенин, группа 6511 From 7d746217635755ebe45469f717221a627290681e Mon Sep 17 00:00:00 2001 From: Dmitri Date: Mon, 16 Feb 2026 15:47:37 +0400 Subject: [PATCH 07/10] =?UTF-8?q?=D0=97=D0=B0=D0=B1=D1=8B=D0=BB=20=D0=B5?= =?UTF-8?q?=D1=89=D0=B5=20=5Flogger=20=D1=83=D0=B1=D1=80=D0=B0=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Services/CreditApplicationService.cs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/CreditApplication.Generator/Services/CreditApplicationService.cs b/CreditApplication.Generator/Services/CreditApplicationService.cs index fcf41bd..2461ddd 100644 --- a/CreditApplication.Generator/Services/CreditApplicationService.cs +++ b/CreditApplication.Generator/Services/CreditApplicationService.cs @@ -15,7 +15,6 @@ public class CreditApplicationService( { private readonly CreditApplicationGenerator _generator = generator; private readonly IDistributedCache _cache = cache; - private readonly ILogger _logger = logger; private readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes( configuration.GetValue("CacheSettings:ExpirationMinutes", 5)); @@ -29,13 +28,13 @@ public async Task GetByIdAsync(int id, CancellationToken { var cacheKey = $"{CacheKeyPrefix}{id}"; - _logger.LogInformation("Request for credit application with ID: {Id}", id); + logger.LogInformation("Request for credit application with ID: {Id}", id); var cachedData = await _cache.GetStringAsync(cacheKey, cancellationToken); if (!string.IsNullOrEmpty(cachedData)) { - _logger.LogInformation("Credit application {Id} found in cache", id); + logger.LogInformation("Credit application {Id} found in cache", id); var cachedApplication = JsonSerializer.Deserialize(cachedData); if (cachedApplication is not null) @@ -43,10 +42,10 @@ public async Task GetByIdAsync(int id, CancellationToken return cachedApplication; } - _logger.LogWarning("Cached data for credit application {Id} deserialized to null, regenerating", id); + logger.LogWarning("Cached data for credit application {Id} deserialized to null, regenerating", id); } - _logger.LogInformation("Credit application {Id} not found in cache, generating new one", id); + logger.LogInformation("Credit application {Id} not found in cache, generating new one", id); var application = _generator.Generate(id); @@ -58,7 +57,7 @@ public async Task GetByIdAsync(int id, CancellationToken await _cache.SetStringAsync(cacheKey, serializedData, cacheOptions, cancellationToken); - _logger.LogInformation( + logger.LogInformation( "Credit application {Id} saved to cache with TTL {CacheExpiration} minutes", id, _cacheExpiration.TotalMinutes); From 089ed21367c49371ff14efe659ac3b6010973a17 Mon Sep 17 00:00:00 2001 From: Dmitri Date: Wed, 18 Feb 2026 14:39:27 +0400 Subject: [PATCH 08/10] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=B0=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.sln | 50 ++++++++++++++++ .../CreditApplication.AppHost.csproj | 1 + CreditApplication.AppHost/Program.cs | 35 ++++++++++-- .../CreditApplication.Gateway.csproj | 17 ++++++ .../WeightedRandomLoadBalancer.cs | 57 +++++++++++++++++++ CreditApplication.Gateway/Program.cs | 48 ++++++++++++++++ .../Properties/launchSettings.json | 14 +++++ .../appsettings.Development.json | 12 ++++ CreditApplication.Gateway/appsettings.json | 11 ++++ CreditApplication.Gateway/ocelot.json | 25 ++++++++ CreditApplication.Generator/Program.cs | 19 ------- CreditApplication.Generator/appsettings.json | 3 +- .../Extensions.cs | 46 ++++++++++++++- 14 files changed, 311 insertions(+), 29 deletions(-) create mode 100644 CreditApplication.Gateway/CreditApplication.Gateway.csproj create mode 100644 CreditApplication.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs create mode 100644 CreditApplication.Gateway/Program.cs create mode 100644 CreditApplication.Gateway/Properties/launchSettings.json create mode 100644 CreditApplication.Gateway/appsettings.Development.json create mode 100644 CreditApplication.Gateway/appsettings.json create mode 100644 CreditApplication.Gateway/ocelot.json diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index 463eb0e..adbd1fa 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "https://localhost:7171/credit-application" + "BaseAddress": "http://localhost:5200/credit-application" } \ No newline at end of file diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index 0ce0c90..691b714 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -11,28 +11,78 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApplication.Generator EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApplication.ServiceDefaults", "CreditApplication.ServiceDefaults\CreditApplication.ServiceDefaults.csproj", "{3E99472D-C53C-A52E-DCDC-C663DE0B4459}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApplication.Gateway", "CreditApplication.Gateway\CreditApplication.Gateway.csproj", "{9455D133-4C88-48D6-AECD-6F84F7E17952}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|x64.ActiveCfg = Debug|Any CPU + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|x64.Build.0 = Debug|Any CPU + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|x86.ActiveCfg = Debug|Any CPU + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|x86.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 + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|x64.ActiveCfg = Release|Any CPU + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|x64.Build.0 = Release|Any CPU + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|x86.ActiveCfg = Release|Any CPU + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|x86.Build.0 = Release|Any CPU {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Debug|x64.ActiveCfg = Debug|Any CPU + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Debug|x64.Build.0 = Debug|Any CPU + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Debug|x86.ActiveCfg = Debug|Any CPU + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Debug|x86.Build.0 = Debug|Any CPU {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Release|Any CPU.ActiveCfg = Release|Any CPU {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Release|Any CPU.Build.0 = Release|Any CPU + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Release|x64.ActiveCfg = Release|Any CPU + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Release|x64.Build.0 = Release|Any CPU + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Release|x86.ActiveCfg = Release|Any CPU + {8D7BA58C-B453-616F-C170-8D20E1B277D5}.Release|x86.Build.0 = Release|Any CPU {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Debug|x64.ActiveCfg = Debug|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Debug|x64.Build.0 = Debug|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Debug|x86.ActiveCfg = Debug|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Debug|x86.Build.0 = Debug|Any CPU {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Release|Any CPU.ActiveCfg = Release|Any CPU {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Release|Any CPU.Build.0 = Release|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Release|x64.ActiveCfg = Release|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Release|x64.Build.0 = Release|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Release|x86.ActiveCfg = Release|Any CPU + {795D187F-BDDB-12D5-574B-DB27A6FAA1B2}.Release|x86.Build.0 = Release|Any CPU {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Debug|x64.ActiveCfg = Debug|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Debug|x64.Build.0 = Debug|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Debug|x86.ActiveCfg = Debug|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Debug|x86.Build.0 = Debug|Any CPU {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Release|Any CPU.ActiveCfg = Release|Any CPU {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Release|Any CPU.Build.0 = Release|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Release|x64.ActiveCfg = Release|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Release|x64.Build.0 = Release|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Release|x86.ActiveCfg = Release|Any CPU + {3E99472D-C53C-A52E-DCDC-C663DE0B4459}.Release|x86.Build.0 = Release|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Debug|x64.ActiveCfg = Debug|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Debug|x64.Build.0 = Debug|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Debug|x86.ActiveCfg = Debug|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Debug|x86.Build.0 = Debug|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Release|Any CPU.Build.0 = Release|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Release|x64.ActiveCfg = Release|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Release|x64.Build.0 = Release|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Release|x86.ActiveCfg = Release|Any CPU + {9455D133-4C88-48D6-AECD-6F84F7E17952}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CreditApplication.AppHost/CreditApplication.AppHost.csproj b/CreditApplication.AppHost/CreditApplication.AppHost.csproj index ad13098..ec0c4a4 100644 --- a/CreditApplication.AppHost/CreditApplication.AppHost.csproj +++ b/CreditApplication.AppHost/CreditApplication.AppHost.csproj @@ -17,6 +17,7 @@ + diff --git a/CreditApplication.AppHost/Program.cs b/CreditApplication.AppHost/Program.cs index 260ea2c..ec6c392 100644 --- a/CreditApplication.AppHost/Program.cs +++ b/CreditApplication.AppHost/Program.cs @@ -1,13 +1,36 @@ -var builder = DistributedApplication.CreateBuilder(args); +using Microsoft.Extensions.Hosting; -var redis = builder.AddRedis("redis") - .WithRedisCommander(); +var builder = DistributedApplication.CreateBuilder(args); -var generator = builder.AddProject("generator") - .WithReference(redis) +var redis = builder.AddRedis("redis"); + +if (builder.Environment.IsDevelopment()) + redis.WithRedisCommander(); + +var generator1 = builder.AddProject("generator-1") + .WithEndpoint("http", endpoint => endpoint.Port = 5101) + .WithHttpHealthCheck("/health") + .WithReference(redis); + +var generator2 = builder.AddProject("generator-2") + .WithEndpoint("http", endpoint => endpoint.Port = 5102) + .WithHttpHealthCheck("/health") + .WithReference(redis); + +var generator3 = builder.AddProject("generator-3") + .WithEndpoint("http", endpoint => endpoint.Port = 5103) + .WithHttpHealthCheck("/health") + .WithReference(redis); + +var gateway = builder.AddProject("gateway") + .WithEndpoint("http", endpoint => endpoint.Port = 5200) + .WithHttpHealthCheck("/health") + .WithReference(generator1) + .WithReference(generator2) + .WithReference(generator3) .WithExternalHttpEndpoints(); builder.AddProject("client") - .WithReference(generator); + .WithReference(gateway); builder.Build().Run(); diff --git a/CreditApplication.Gateway/CreditApplication.Gateway.csproj b/CreditApplication.Gateway/CreditApplication.Gateway.csproj new file mode 100644 index 0000000..27def80 --- /dev/null +++ b/CreditApplication.Gateway/CreditApplication.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/CreditApplication.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs b/CreditApplication.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs new file mode 100644 index 0000000..a72a007 --- /dev/null +++ b/CreditApplication.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs @@ -0,0 +1,57 @@ +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Responses; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Values; + +namespace CreditApplication.Gateway.LoadBalancing; + +public sealed class WeightedRandomLoadBalancer : ILoadBalancer +{ + private readonly IServiceDiscoveryProvider _serviceDiscovery; + private readonly IReadOnlyDictionary _weights; + + public WeightedRandomLoadBalancer( + IServiceDiscoveryProvider serviceDiscovery, + IReadOnlyDictionary weights) + { + _serviceDiscovery = serviceDiscovery; + _weights = weights; + } + + public async Task> Lease(HttpContext httpContext) + { + var services = await _serviceDiscovery.GetAsync(); + + if (services is null) + return new ErrorResponse( + new ServicesAreNullError("Service discovery returned null")); + + if (services.Count == 0) + return new ErrorResponse( + new ServicesAreNullError("No downstream services are available")); + + var weighted = services + .Select(s => ( + Service: s, + Weight: _weights.TryGetValue( + $"{s.HostAndPort.DownstreamHost}:{s.HostAndPort.DownstreamPort}", + out var w) ? w : 1.0)) + .ToList(); + + var total = weighted.Sum(x => x.Weight); + var roll = Random.Shared.NextDouble() * total; + + var cumulative = 0.0; + foreach (var (service, weight) in weighted) + { + cumulative += weight; + if (roll < cumulative) + return new OkResponse(service.HostAndPort); + } + + return new OkResponse(weighted[^1].Service.HostAndPort); + } + + // No connection tracking needed for stateless weighted random load balancing. + public void Release(ServiceHostAndPort hostAndPort) { } +} diff --git a/CreditApplication.Gateway/Program.cs b/CreditApplication.Gateway/Program.cs new file mode 100644 index 0000000..b49c0c3 --- /dev/null +++ b/CreditApplication.Gateway/Program.cs @@ -0,0 +1,48 @@ +using CreditApplication.Gateway.LoadBalancing; +using CreditApplication.ServiceDefaults; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddGatewayDefaults(); + +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); + +var generatorNames = builder.Configuration.GetSection("GeneratorServices").Get() ?? []; +var addressOverrides = new List>(); +for (var i = 0; i < generatorNames.Length; i++) +{ + var url = builder.Configuration[$"services:{generatorNames[i]}:http:0"]; + if (!string.IsNullOrEmpty(url) && Uri.TryCreate(url, UriKind.Absolute, out var uri)) + { + addressOverrides.Add(new($"Routes:0:DownstreamHostAndPorts:{i}:Host", uri.Host)); + addressOverrides.Add(new($"Routes:0:DownstreamHostAndPorts:{i}:Port", uri.Port.ToString())); + } +} +if (addressOverrides.Count > 0) + builder.Configuration.AddInMemoryCollection(addressOverrides); + +var weights = builder.Configuration + .GetSection("ReplicaWeights") + .Get>() ?? new Dictionary(); + +builder.Services + .AddOcelot(builder.Configuration) + .AddCustomLoadBalancer((route, serviceDiscovery) => + new WeightedRandomLoadBalancer(serviceDiscovery, weights)); + +var app = builder.Build(); + +app.UseCors(); + +app.UseHealthChecks("/health"); +app.UseHealthChecks("/alive", new HealthCheckOptions +{ + Predicate = r => r.Tags.Contains("live") +}); + +await app.UseOcelot(); + +app.Run(); diff --git a/CreditApplication.Gateway/Properties/launchSettings.json b/CreditApplication.Gateway/Properties/launchSettings.json new file mode 100644 index 0000000..fa81b2a --- /dev/null +++ b/CreditApplication.Gateway/Properties/launchSettings.json @@ -0,0 +1,14 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5200", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CreditApplication.Gateway/appsettings.Development.json b/CreditApplication.Gateway/appsettings.Development.json new file mode 100644 index 0000000..75bf87c --- /dev/null +++ b/CreditApplication.Gateway/appsettings.Development.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Ocelot": "Debug" + } + }, + "GlobalConfiguration": { + "BaseUrl": "http://localhost:5200" + } +} diff --git a/CreditApplication.Gateway/appsettings.json b/CreditApplication.Gateway/appsettings.json new file mode 100644 index 0000000..d0a485d --- /dev/null +++ b/CreditApplication.Gateway/appsettings.json @@ -0,0 +1,11 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Ocelot": "Information" + } + }, + "AllowedHosts": "*", + "CorsAllowedOrigins": [] +} diff --git a/CreditApplication.Gateway/ocelot.json b/CreditApplication.Gateway/ocelot.json new file mode 100644 index 0000000..8921cd8 --- /dev/null +++ b/CreditApplication.Gateway/ocelot.json @@ -0,0 +1,25 @@ +{ + "GeneratorServices": [ "generator-1", "generator-2", "generator-3" ], + "Routes": [ + { + "DownstreamPathTemplate": "/credit-application", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { "Host": "localhost", "Port": 5101 }, + { "Host": "localhost", "Port": 5102 }, + { "Host": "localhost", "Port": 5103 } + ], + "UpstreamPathTemplate": "/credit-application", + "UpstreamHttpMethod": [ "Get" ], + "LoadBalancerOptions": { + "Type": "WeightedRandomLoadBalancer" + } + } + ], + "ReplicaWeights": { + "localhost:5101": 0.5, + "localhost:5102": 0.3, + "localhost:5103": 0.2 + }, + "GlobalConfiguration": {} +} diff --git a/CreditApplication.Generator/Program.cs b/CreditApplication.Generator/Program.cs index bc3a7b3..79aedf4 100644 --- a/CreditApplication.Generator/Program.cs +++ b/CreditApplication.Generator/Program.cs @@ -11,25 +11,6 @@ builder.Services.AddSingleton(); builder.Services.AddScoped(); -builder.Services.AddCors(options => -{ - options.AddDefaultPolicy(policy => - { - if (builder.Environment.IsDevelopment()) - { - policy.AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader(); - } - else - { - policy.WithOrigins("https://your-production-frontend.example") - .WithMethods("GET") - .WithHeaders("Content-Type", "Authorization"); - } - }); -}); - var app = builder.Build(); app.UseCors(); diff --git a/CreditApplication.Generator/appsettings.json b/CreditApplication.Generator/appsettings.json index a9ceb83..75cc167 100644 --- a/CreditApplication.Generator/appsettings.json +++ b/CreditApplication.Generator/appsettings.json @@ -7,5 +7,6 @@ }, "CacheSettings": { "ExpirationMinutes": 5 - } + }, + "CorsAllowedOrigins": [] } diff --git a/CreditApplication.ServiceDefaults/Extensions.cs b/CreditApplication.ServiceDefaults/Extensions.cs index d38113f..43c038d 100644 --- a/CreditApplication.ServiceDefaults/Extensions.cs +++ b/CreditApplication.ServiceDefaults/Extensions.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; @@ -18,6 +19,7 @@ public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBu builder.ConfigureSerilog(); builder.ConfigureOpenTelemetry(); builder.AddDefaultHealthChecks(); + builder.AddDefaultCors(); builder.Services.AddServiceDiscovery(); builder.Services.ConfigureHttpClientDefaults(http => { @@ -62,8 +64,10 @@ public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicati }) .WithTracing(tracing => { - tracing.AddAspNetCoreInstrumentation() - .AddHttpClientInstrumentation(); + tracing.AddAspNetCoreInstrumentation(options => + { + options.Filter = ctx => ctx.Request.Path != "/health"; + }); }); builder.AddOpenTelemetryExporters(); @@ -91,6 +95,44 @@ public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicati return builder; } + public static IHostApplicationBuilder AddGatewayDefaults(this IHostApplicationBuilder builder) + { + builder.ConfigureSerilog(); + builder.ConfigureOpenTelemetry(); + builder.AddDefaultHealthChecks(); + builder.AddDefaultCors(); + + return builder; + } + + public static IHostApplicationBuilder AddDefaultCors(this IHostApplicationBuilder builder) + { + builder.Services.AddCors(options => + { + options.AddDefaultPolicy(policy => + { + if (builder.Environment.IsDevelopment()) + { + policy.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + } + else + { + var allowedOrigins = builder.Configuration + .GetSection("CorsAllowedOrigins") + .Get() ?? []; + + policy.WithOrigins(allowedOrigins) + .WithMethods("GET") + .WithHeaders("Content-Type", "Authorization"); + } + }); + }); + + return builder; + } + public static WebApplication MapDefaultEndpoints(this WebApplication app) { app.MapHealthChecks("/health"); From 700e4da2049adb0cf2a671d1f32d1cdad110ba3e Mon Sep 17 00:00:00 2001 From: Dmitri Date: Wed, 18 Feb 2026 15:17:38 +0400 Subject: [PATCH 09/10] =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81=20=D0=BF=D1=80?= =?UTF-8?q?=D0=B0=D0=B2=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CreditApplication.AppHost/Program.cs | 6 ++++-- CreditApplication.Generator/Program.cs | 6 +++++- .../Services/CreditApplicationGenerator.cs | 2 +- .../Services/CreditApplicationService.cs | 15 ++++++--------- CreditApplication.Generator/appsettings.json | 5 +++++ .../CreditApplication.ServiceDefaults.csproj | 2 +- 6 files changed, 22 insertions(+), 14 deletions(-) diff --git a/CreditApplication.AppHost/Program.cs b/CreditApplication.AppHost/Program.cs index 260ea2c..263f622 100644 --- a/CreditApplication.AppHost/Program.cs +++ b/CreditApplication.AppHost/Program.cs @@ -5,9 +5,11 @@ var generator = builder.AddProject("generator") .WithReference(redis) - .WithExternalHttpEndpoints(); + .WithExternalHttpEndpoints() + .WaitFor(redis); builder.AddProject("client") - .WithReference(generator); + .WithReference(generator) + .WaitFor(generator); builder.Build().Run(); diff --git a/CreditApplication.Generator/Program.cs b/CreditApplication.Generator/Program.cs index bc3a7b3..59a3648 100644 --- a/CreditApplication.Generator/Program.cs +++ b/CreditApplication.Generator/Program.cs @@ -23,7 +23,11 @@ } else { - policy.WithOrigins("https://your-production-frontend.example") + var allowedOrigins = builder.Configuration + .GetSection("Cors:AllowedOrigins") + .Get() ?? []; + + policy.WithOrigins(allowedOrigins) .WithMethods("GET") .WithHeaders("Content-Type", "Authorization"); } diff --git a/CreditApplication.Generator/Services/CreditApplicationGenerator.cs b/CreditApplication.Generator/Services/CreditApplicationGenerator.cs index 9075ca0..4acf770 100644 --- a/CreditApplication.Generator/Services/CreditApplicationGenerator.cs +++ b/CreditApplication.Generator/Services/CreditApplicationGenerator.cs @@ -51,7 +51,7 @@ public CreditApplicationModel Generate(int id) .FinishWith(SetStatusDependentFields); var application = faker.Generate(); - + logger.LogInformation( "Credit application generated: ID={Id}, Type={CreditType}, Status={Status}, Amount={Amount}", application.Id, diff --git a/CreditApplication.Generator/Services/CreditApplicationService.cs b/CreditApplication.Generator/Services/CreditApplicationService.cs index 2461ddd..09414f8 100644 --- a/CreditApplication.Generator/Services/CreditApplicationService.cs +++ b/CreditApplication.Generator/Services/CreditApplicationService.cs @@ -13,11 +13,8 @@ public class CreditApplicationService( IConfiguration configuration, ILogger logger) { - private readonly CreditApplicationGenerator _generator = generator; - private readonly IDistributedCache _cache = cache; - private readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes( - configuration.GetValue("CacheSettings:ExpirationMinutes", 5)); + configuration.GetValue("CacheSettings:ExpirationMinutes", 5)); private const string CacheKeyPrefix = "credit-application:"; /// @@ -30,24 +27,24 @@ public async Task GetByIdAsync(int id, CancellationToken logger.LogInformation("Request for credit application with ID: {Id}", id); - var cachedData = await _cache.GetStringAsync(cacheKey, cancellationToken); + var cachedData = await cache.GetStringAsync(cacheKey, cancellationToken); if (!string.IsNullOrEmpty(cachedData)) { logger.LogInformation("Credit application {Id} found in cache", id); var cachedApplication = JsonSerializer.Deserialize(cachedData); - + if (cachedApplication is not null) { return cachedApplication; } - + logger.LogWarning("Cached data for credit application {Id} deserialized to null, regenerating", id); } logger.LogInformation("Credit application {Id} not found in cache, generating new one", id); - var application = _generator.Generate(id); + var application = generator.Generate(id); var serializedData = JsonSerializer.Serialize(application); var cacheOptions = new DistributedCacheEntryOptions @@ -55,7 +52,7 @@ public async Task GetByIdAsync(int id, CancellationToken AbsoluteExpirationRelativeToNow = _cacheExpiration }; - await _cache.SetStringAsync(cacheKey, serializedData, cacheOptions, cancellationToken); + await cache.SetStringAsync(cacheKey, serializedData, cacheOptions, cancellationToken); logger.LogInformation( "Credit application {Id} saved to cache with TTL {CacheExpiration} minutes", diff --git a/CreditApplication.Generator/appsettings.json b/CreditApplication.Generator/appsettings.json index a9ceb83..ee028f8 100644 --- a/CreditApplication.Generator/appsettings.json +++ b/CreditApplication.Generator/appsettings.json @@ -7,5 +7,10 @@ }, "CacheSettings": { "ExpirationMinutes": 5 + }, + "Cors": { + "AllowedOrigins": [ + "https://your-production-frontend.example" + ] } } diff --git a/CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj b/CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj index 7cd1cfd..942bf8d 100644 --- a/CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj +++ b/CreditApplication.ServiceDefaults/CreditApplication.ServiceDefaults.csproj @@ -12,7 +12,7 @@ - + From 2f7c365663f7b6216e9331c6cd7579cfdde1593b Mon Sep 17 00:00:00 2001 From: Dmitri Date: Wed, 18 Feb 2026 16:16:01 +0400 Subject: [PATCH 10/10] =?UTF-8?q?=D0=B5=D1=89=D0=B5=20=D0=BE=D0=B4=D0=B8?= =?UTF-8?q?=D0=BD=20=D0=BA=D0=BE=D0=BC=D0=BC=D0=B8=D1=82=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D1=81=D0=BB=D0=B8=D1=8F=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CreditApplication.AppHost/Program.cs | 12 ++++---- .../WeightedRandomLoadBalancer.cs | 17 +++++++++-- CreditApplication.Gateway/Program.cs | 28 ++++++++++++++++--- CreditApplication.Gateway/appsettings.json | 7 +++-- CreditApplication.Generator/Program.cs | 1 - .../Properties/launchSettings.json | 9 ------ .../Services/CreditApplicationGenerator.cs | 2 +- .../Services/CreditApplicationService.cs | 13 +++++++-- CreditApplication.Generator/appsettings.json | 5 ---- .../Extensions.cs | 6 ++-- 10 files changed, 62 insertions(+), 38 deletions(-) diff --git a/CreditApplication.AppHost/Program.cs b/CreditApplication.AppHost/Program.cs index ec6c392..676b193 100644 --- a/CreditApplication.AppHost/Program.cs +++ b/CreditApplication.AppHost/Program.cs @@ -9,28 +9,28 @@ var generator1 = builder.AddProject("generator-1") .WithEndpoint("http", endpoint => endpoint.Port = 5101) - .WithHttpHealthCheck("/health") .WithReference(redis); var generator2 = builder.AddProject("generator-2") .WithEndpoint("http", endpoint => endpoint.Port = 5102) - .WithHttpHealthCheck("/health") .WithReference(redis); var generator3 = builder.AddProject("generator-3") .WithEndpoint("http", endpoint => endpoint.Port = 5103) - .WithHttpHealthCheck("/health") .WithReference(redis); var gateway = builder.AddProject("gateway") .WithEndpoint("http", endpoint => endpoint.Port = 5200) - .WithHttpHealthCheck("/health") .WithReference(generator1) .WithReference(generator2) .WithReference(generator3) - .WithExternalHttpEndpoints(); + .WithExternalHttpEndpoints() + .WaitFor(generator1) + .WaitFor(generator2) + .WaitFor(generator3); builder.AddProject("client") - .WithReference(gateway); + .WithReference(gateway) + .WaitFor(gateway); builder.Build().Run(); diff --git a/CreditApplication.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs b/CreditApplication.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs index a72a007..a16a893 100644 --- a/CreditApplication.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs +++ b/CreditApplication.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs @@ -30,6 +30,11 @@ public async Task> Lease(HttpContext httpContext) return new ErrorResponse( new ServicesAreNullError("No downstream services are available")); + return new OkResponse(SelectByWeight(services).HostAndPort); + } + + private Service SelectByWeight(IList services) + { var weighted = services .Select(s => ( Service: s, @@ -39,17 +44,23 @@ public async Task> Lease(HttpContext httpContext) .ToList(); var total = weighted.Sum(x => x.Weight); - var roll = Random.Shared.NextDouble() * total; + // If all weights are zero or missing, fall back to uniform random selection. + if (total <= 0) + return services[Random.Shared.Next(services.Count)]; + + var roll = Random.Shared.NextDouble() * total; var cumulative = 0.0; + foreach (var (service, weight) in weighted) { cumulative += weight; if (roll < cumulative) - return new OkResponse(service.HostAndPort); + return service; } - return new OkResponse(weighted[^1].Service.HostAndPort); + // Guard against floating-point rounding: cumulative may fall infinitesimally short of total. + return weighted[^1].Service; } // No connection tracking needed for stateless weighted random load balancing. diff --git a/CreditApplication.Gateway/Program.cs b/CreditApplication.Gateway/Program.cs index b49c0c3..2ec4304 100644 --- a/CreditApplication.Gateway/Program.cs +++ b/CreditApplication.Gateway/Program.cs @@ -8,6 +8,29 @@ builder.AddGatewayDefaults(); +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + { + if (builder.Environment.IsDevelopment()) + { + policy.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + } + else + { + var allowedOrigins = builder.Configuration + .GetSection("Cors:AllowedOrigins") + .Get() ?? []; + + policy.WithOrigins(allowedOrigins) + .WithMethods("GET") + .WithHeaders("Content-Type", "Authorization"); + } + }); +}); + builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); var generatorNames = builder.Configuration.GetSection("GeneratorServices").Get() ?? []; @@ -38,10 +61,7 @@ app.UseCors(); app.UseHealthChecks("/health"); -app.UseHealthChecks("/alive", new HealthCheckOptions -{ - Predicate = r => r.Tags.Contains("live") -}); +app.UseHealthChecks("/alive", new HealthCheckOptions { Predicate = r => r.Tags.Contains("live") }); await app.UseOcelot(); diff --git a/CreditApplication.Gateway/appsettings.json b/CreditApplication.Gateway/appsettings.json index d0a485d..c3353d7 100644 --- a/CreditApplication.Gateway/appsettings.json +++ b/CreditApplication.Gateway/appsettings.json @@ -6,6 +6,9 @@ "Ocelot": "Information" } }, - "AllowedHosts": "*", - "CorsAllowedOrigins": [] + "Cors": { + "AllowedOrigins": [ + "https://your-production-frontend.example" + ] + } } diff --git a/CreditApplication.Generator/Program.cs b/CreditApplication.Generator/Program.cs index 79aedf4..5bff9bb 100644 --- a/CreditApplication.Generator/Program.cs +++ b/CreditApplication.Generator/Program.cs @@ -13,7 +13,6 @@ var app = builder.Build(); -app.UseCors(); app.UseSerilogRequestLogging(); app.MapDefaultEndpoints(); diff --git a/CreditApplication.Generator/Properties/launchSettings.json b/CreditApplication.Generator/Properties/launchSettings.json index ea1476c..8c4696c 100644 --- a/CreditApplication.Generator/Properties/launchSettings.json +++ b/CreditApplication.Generator/Properties/launchSettings.json @@ -9,15 +9,6 @@ "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } - }, - "https": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": false, - "applicationUrl": "https://localhost:7171;http://localhost:5171", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } } } } diff --git a/CreditApplication.Generator/Services/CreditApplicationGenerator.cs b/CreditApplication.Generator/Services/CreditApplicationGenerator.cs index 4acf770..55c96bf 100644 --- a/CreditApplication.Generator/Services/CreditApplicationGenerator.cs +++ b/CreditApplication.Generator/Services/CreditApplicationGenerator.cs @@ -27,7 +27,7 @@ public class CreditApplicationGenerator(ILogger logg "Отклонена" ]; - private static readonly string[] _terminalStatuses = ["Одобрена", "Отклонена"]; + private static readonly HashSet _terminalStatuses = ["Одобрена", "Отклонена"]; /// /// Генерирует кредитную заявку по указанному идентификатору diff --git a/CreditApplication.Generator/Services/CreditApplicationService.cs b/CreditApplication.Generator/Services/CreditApplicationService.cs index 09414f8..6a4e89b 100644 --- a/CreditApplication.Generator/Services/CreditApplicationService.cs +++ b/CreditApplication.Generator/Services/CreditApplicationService.cs @@ -32,13 +32,20 @@ public async Task GetByIdAsync(int id, CancellationToken if (!string.IsNullOrEmpty(cachedData)) { logger.LogInformation("Credit application {Id} found in cache", id); - var cachedApplication = JsonSerializer.Deserialize(cachedData); - if (cachedApplication is not null) + CreditApplicationModel? cachedApplication = null; + try { - return cachedApplication; + cachedApplication = JsonSerializer.Deserialize(cachedData); + } + catch (JsonException ex) + { + logger.LogWarning(ex, "Failed to deserialize cached credit application {Id}, regenerating", id); } + if (cachedApplication is not null) + return cachedApplication; + logger.LogWarning("Cached data for credit application {Id} deserialized to null, regenerating", id); } diff --git a/CreditApplication.Generator/appsettings.json b/CreditApplication.Generator/appsettings.json index ee028f8..a9ceb83 100644 --- a/CreditApplication.Generator/appsettings.json +++ b/CreditApplication.Generator/appsettings.json @@ -7,10 +7,5 @@ }, "CacheSettings": { "ExpirationMinutes": 5 - }, - "Cors": { - "AllowedOrigins": [ - "https://your-production-frontend.example" - ] } } diff --git a/CreditApplication.ServiceDefaults/Extensions.cs b/CreditApplication.ServiceDefaults/Extensions.cs index 43c038d..9485bcb 100644 --- a/CreditApplication.ServiceDefaults/Extensions.cs +++ b/CreditApplication.ServiceDefaults/Extensions.cs @@ -64,10 +64,8 @@ public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicati }) .WithTracing(tracing => { - tracing.AddAspNetCoreInstrumentation(options => - { - options.Filter = ctx => ctx.Request.Path != "/health"; - }); + tracing.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation(); }); builder.AddOpenTelemetryExporters();