diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..b6fa4aa0 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №3 "Интеграционное тестирование" + Вариант №15 "Балансировка нагрузки" + Выполнил Сукач Данил 6511 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea7..60120ec3 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:5127", "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:7282;http://localhost:5127", "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/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index 4dda7c04..a3058987 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "https://localhost:7170/land-plot" + "BaseAddress": "https://localhost:7201/api/Credit" } \ No newline at end of file diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..b3d469de 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -1,10 +1,28 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.14.36811.4 +# Visual Studio Version 18 +VisualStudioVersion = 18.3.11505.172 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}") = "CreditApp.AppHost", "CreditApp\CreditApp.AppHost\CreditApp.AppHost.csproj", "{595C6305-ACA3-4E87-8CBF-27A4C92BAE97}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.ServiceDefaults", "CreditApp\CreditApp.ServiceDefaults\CreditApp.ServiceDefaults.csproj", "{A7B14B5D-B738-B77E-404F-CF5182E30A41}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.Api", "CreditApp.Api\CreditApp.Api.csproj", "{E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.Domain", "CreditApp.Domain\CreditApp.Domain.csproj", "{2B736CD0-1260-4F6F-854F-5F35E0CBC260}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.Application", "CreditApp.Application\CreditApp.Application.csproj", "{69FCFAEE-907C-4365-897A-EF120A644131}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.Infrastructure", "CreditApp.Infrastructure\CreditApp.Infrastructure.csproj", "{C5A26B57-58ED-45E9-9371-AAF64F30C3A8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.Gateway", "CreditApp.Gateway\CreditApp.Gateway.csproj", "{3BA8A38C-6AFF-C134-67A1-BC28FDD7ACF1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.FileService", "CreditApp.FileService\CreditApp.FileService.csproj", "{9FB93C0A-039C-9B30-1599-38D087B50EBF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.IntegrationTests", "CreditApp.IntegrationTests\CreditApp.IntegrationTests.csproj", "{A43154C5-BAD4-438C-BF07-DFCA7F60C1B4}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +33,42 @@ 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 + {595C6305-ACA3-4E87-8CBF-27A4C92BAE97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {595C6305-ACA3-4E87-8CBF-27A4C92BAE97}.Debug|Any CPU.Build.0 = Debug|Any CPU + {595C6305-ACA3-4E87-8CBF-27A4C92BAE97}.Release|Any CPU.ActiveCfg = Release|Any CPU + {595C6305-ACA3-4E87-8CBF-27A4C92BAE97}.Release|Any CPU.Build.0 = Release|Any CPU + {A7B14B5D-B738-B77E-404F-CF5182E30A41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A7B14B5D-B738-B77E-404F-CF5182E30A41}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A7B14B5D-B738-B77E-404F-CF5182E30A41}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A7B14B5D-B738-B77E-404F-CF5182E30A41}.Release|Any CPU.Build.0 = Release|Any CPU + {E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Release|Any CPU.Build.0 = Release|Any CPU + {2B736CD0-1260-4F6F-854F-5F35E0CBC260}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2B736CD0-1260-4F6F-854F-5F35E0CBC260}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2B736CD0-1260-4F6F-854F-5F35E0CBC260}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2B736CD0-1260-4F6F-854F-5F35E0CBC260}.Release|Any CPU.Build.0 = Release|Any CPU + {69FCFAEE-907C-4365-897A-EF120A644131}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {69FCFAEE-907C-4365-897A-EF120A644131}.Debug|Any CPU.Build.0 = Debug|Any CPU + {69FCFAEE-907C-4365-897A-EF120A644131}.Release|Any CPU.ActiveCfg = Release|Any CPU + {69FCFAEE-907C-4365-897A-EF120A644131}.Release|Any CPU.Build.0 = Release|Any CPU + {C5A26B57-58ED-45E9-9371-AAF64F30C3A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C5A26B57-58ED-45E9-9371-AAF64F30C3A8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C5A26B57-58ED-45E9-9371-AAF64F30C3A8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C5A26B57-58ED-45E9-9371-AAF64F30C3A8}.Release|Any CPU.Build.0 = Release|Any CPU + {3BA8A38C-6AFF-C134-67A1-BC28FDD7ACF1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3BA8A38C-6AFF-C134-67A1-BC28FDD7ACF1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3BA8A38C-6AFF-C134-67A1-BC28FDD7ACF1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3BA8A38C-6AFF-C134-67A1-BC28FDD7ACF1}.Release|Any CPU.Build.0 = Release|Any CPU + {9FB93C0A-039C-9B30-1599-38D087B50EBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9FB93C0A-039C-9B30-1599-38D087B50EBF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9FB93C0A-039C-9B30-1599-38D087B50EBF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9FB93C0A-039C-9B30-1599-38D087B50EBF}.Release|Any CPU.Build.0 = Release|Any CPU + {A43154C5-BAD4-438C-BF07-DFCA7F60C1B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A43154C5-BAD4-438C-BF07-DFCA7F60C1B4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A43154C5-BAD4-438C-BF07-DFCA7F60C1B4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A43154C5-BAD4-438C-BF07-DFCA7F60C1B4}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CreditApp.Api/Controllers/CreditController.cs b/CreditApp.Api/Controllers/CreditController.cs new file mode 100644 index 00000000..e0e232b5 --- /dev/null +++ b/CreditApp.Api/Controllers/CreditController.cs @@ -0,0 +1,39 @@ +using CreditApp.Application.Interfaces; +using CreditApp.Domain.Entities; +using Microsoft.AspNetCore.Mvc; + +namespace CreditApp.Api.Controllers; + +/// +/// Контроллер для работы с кредитными заявками через HTTP API. +/// Реализует конечную точку получения заявки по идентификатору. +/// Сервис для получения данных кредитных заявок. +/// Логгер для записи событий и ошибок. +/// +[Route("api/[controller]")] +[ApiController] +public class CreditController( + ICreditService creditService, + ILogger logger + ) : ControllerBase +{ + /// + /// Получает кредитную заявку по идентификатору. + /// + /// Идентификатор запрашиваемой заявки (передаётся в строке запроса). + /// Токен отмены для асинхронной операции. + /// HTTP 200 с объектом заявки при успешном получении. + [HttpGet] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> Get([FromQuery] int id, CancellationToken ct) + { + logger.LogInformation("Request for credit {CreditId} started", id); + + var result = await creditService.GetAsync(id, ct); + + logger.LogInformation("Request for credit {CreditId} completed", id); + + return Ok(result); + } +} diff --git a/CreditApp.Api/CreditApp.Api.csproj b/CreditApp.Api/CreditApp.Api.csproj new file mode 100644 index 00000000..28a09937 --- /dev/null +++ b/CreditApp.Api/CreditApp.Api.csproj @@ -0,0 +1,25 @@ + + + + net8.0 + enable + enable + true + $(NoWarn);1591 + + + + + + + + + + + + + + + + + diff --git a/CreditApp.Api/Program.cs b/CreditApp.Api/Program.cs new file mode 100644 index 00000000..f9647b1d --- /dev/null +++ b/CreditApp.Api/Program.cs @@ -0,0 +1,89 @@ +using Amazon.SimpleNotificationService; +using Amazon.SQS; +using CreditApp.Application.Interfaces; +using CreditApp.ServiceDefaults; +using CreditApp.Application.Options; +using CreditApp.Application.Services; +using CreditApp.Infrastructure.Generators; +using MassTransit; +using System.Reflection; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("credit-cache"); + +builder.Services.AddSingleton(); + +builder.Services.Configure( + builder.Configuration.GetSection(CacheOptions.SectionName)); + +builder.Services.AddScoped(); + +var awsServiceUrl = builder.Configuration["Aws:ServiceUrl"] ?? "http://localhost:4566"; +var awsRegion = builder.Configuration["Aws:Region"] ?? "us-east-1"; +var awsAccessKey = builder.Configuration["Aws:AccessKey"] ?? "test"; +var awsSecretKey = builder.Configuration["Aws:SecretKey"] ?? "test"; + +builder.Services.AddMassTransit(x => +{ + x.UsingAmazonSqs((context, cfg) => + { + cfg.Host(awsRegion, h => + { + h.Config(new AmazonSQSConfig { ServiceURL = awsServiceUrl }); + h.Config(new AmazonSimpleNotificationServiceConfig { ServiceURL = awsServiceUrl }); + h.AccessKey(awsAccessKey); + h.SecretKey(awsSecretKey); + }); + + cfg.ConfigureEndpoints(context); + }); +}); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(options => +{ + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + options.IncludeXmlComments(xmlPath); + + var domainXmlPath = Path.Combine(AppContext.BaseDirectory, "CreditApp.Domain.xml"); + if (File.Exists(domainXmlPath)) + options.IncludeXmlComments(domainXmlPath); +}); + +var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get() ?? []; + +builder.Services.AddCors(options => +{ + options.AddPolicy("DefaultCors", policy => + { + policy.AllowAnyHeader().AllowAnyMethod(); + + if (builder.Environment.IsDevelopment()) + policy.AllowAnyOrigin(); + else + policy.WithOrigins(allowedOrigins); + }); +}); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1"); + c.RoutePrefix = string.Empty; + }); +} + +app.UseCors("DefaultCors"); + +app.MapDefaultEndpoints(); +app.MapControllers(); + +app.Run(); diff --git a/CreditApp.Api/Properties/launchSettings.json b/CreditApp.Api/Properties/launchSettings.json new file mode 100644 index 00000000..a9a106e4 --- /dev/null +++ b/CreditApp.Api/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:53917", + "sslPort": 44347 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5022", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7084;http://localhost:5022", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CreditApp.Api/appsettings.Development.json b/CreditApp.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CreditApp.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CreditApp.Api/appsettings.json b/CreditApp.Api/appsettings.json new file mode 100644 index 00000000..2e3f9b31 --- /dev/null +++ b/CreditApp.Api/appsettings.json @@ -0,0 +1,28 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "ConnectionStrings": { + "redis": "localhost:6379" + } + , + "CreditGenerator": { + "CentralBankRate": 16.0 + }, + "Cache": { + "AbsoluteExpirationMinutes": 10 + }, + "Aws": { + "ServiceUrl": "http://localhost:4566", + "Region": "us-east-1", + "AccessKey": "test", + "SecretKey": "test" + }, + "Cors": { + "AllowedOrigins": [ "https://localhost:7282", "http://localhost:7200" ] + } +} diff --git a/CreditApp.Application/CreditApp.Application.csproj b/CreditApp.Application/CreditApp.Application.csproj new file mode 100644 index 00000000..fbc6e77d --- /dev/null +++ b/CreditApp.Application/CreditApp.Application.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + diff --git a/CreditApp.Application/Interfaces/ICreditApplicationGenerator.cs b/CreditApp.Application/Interfaces/ICreditApplicationGenerator.cs new file mode 100644 index 00000000..163c9719 --- /dev/null +++ b/CreditApp.Application/Interfaces/ICreditApplicationGenerator.cs @@ -0,0 +1,17 @@ +using CreditApp.Domain.Entities; + +namespace CreditApp.Application.Interfaces; + +/// +/// Генерирует объекты заявок на кредит для тестирования, заполнения демонстрационных данных или инициализации. +/// Реализации должны создавать и возвращать готовый к использованию экземпляр . +/// +public interface ICreditApplicationGenerator +{ + /// + /// Асинхронно генерирует заявку на кредит с указанным идентификатором. + /// + /// Идентификатор создаваемой заявки. + /// Сгенерированный экземпляр . + public Task GenerateAsync(int id); +} diff --git a/CreditApp.Application/Interfaces/ICreditService.cs b/CreditApp.Application/Interfaces/ICreditService.cs new file mode 100644 index 00000000..213bb4f5 --- /dev/null +++ b/CreditApp.Application/Interfaces/ICreditService.cs @@ -0,0 +1,19 @@ +using CreditApp.Domain.Entities; + +namespace CreditApp.Application.Interfaces; + +/// +/// Сервис для работы с объектами кредитных заявок. +/// Предоставляет операции получения и управления заявками в приложении. +/// +public interface ICreditService +{ + /// + /// Асинхронно получает заявку на кредит по её идентификатору. + /// + /// Идентификатор заявки. + /// Токен отмены для асинхронной операции. + /// Экземпляр , соответствующий запрошенному идентификатору. + public Task GetAsync(int id, CancellationToken ct); + +} diff --git a/CreditApp.Application/Messages/CreditApplicationCreated.cs b/CreditApp.Application/Messages/CreditApplicationCreated.cs new file mode 100644 index 00000000..4d6235b4 --- /dev/null +++ b/CreditApp.Application/Messages/CreditApplicationCreated.cs @@ -0,0 +1,10 @@ +using CreditApp.Domain.Entities; + +namespace CreditApp.Application.Messages; + +/// +/// Сообщение о создании кредитной заявки. +/// Публикуется в SNS-топик для асинхронной обработки файловым сервисом. +/// +/// Сгенерированная кредитная заявка. +public record CreditApplicationCreated(CreditApplication Application); diff --git a/CreditApp.Application/Options/CacheOptions.cs b/CreditApp.Application/Options/CacheOptions.cs new file mode 100644 index 00000000..ede36722 --- /dev/null +++ b/CreditApp.Application/Options/CacheOptions.cs @@ -0,0 +1,8 @@ +namespace CreditApp.Application.Options; + +public class CacheOptions +{ + public const string SectionName = "Cache"; + + public int AbsoluteExpirationMinutes { get; set; } = 10; +} diff --git a/CreditApp.Application/Services/CreditService.cs b/CreditApp.Application/Services/CreditService.cs new file mode 100644 index 00000000..f24f31af --- /dev/null +++ b/CreditApp.Application/Services/CreditService.cs @@ -0,0 +1,70 @@ +using System.Text.Json; +using CreditApp.Application.Interfaces; +using CreditApp.Application.Messages; +using CreditApp.Application.Options; +using CreditApp.Domain.Entities; +using MassTransit; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace CreditApp.Application.Services; + +public class CreditService(IDistributedCache distributedCache, + ICreditApplicationGenerator generator, + IPublishEndpoint publishEndpoint, + IOptions cacheOptions, + ILogger logger) + : ICreditService +{ + public async Task GetAsync(int id, CancellationToken ct) + { + var cacheKey = $"Credit_{id}"; + + try + { + var cached = await distributedCache.GetStringAsync(cacheKey, ct); + + if (!string.IsNullOrEmpty(cached)) + { + var deserialized = JsonSerializer.Deserialize(cached); + if (deserialized is not null) + { + logger.LogInformation("Cache HIT {CacheKey}", cacheKey); + return deserialized; + } + } + } + catch (Exception ex) + { + logger.LogWarning(ex, "Cache read failed for {CacheKey}", cacheKey); + } + + logger.LogInformation("Cache MISS {CacheKey}", cacheKey); + + var credit = await generator.GenerateAsync(id); + + try + { + var options = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(cacheOptions.Value.AbsoluteExpirationMinutes) + }; + + await distributedCache.SetStringAsync( + cacheKey, + JsonSerializer.Serialize(credit), + options, + ct); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Cache write failed for {CacheKey}", cacheKey); + } + + await publishEndpoint.Publish(new CreditApplicationCreated(credit), ct); + logger.LogInformation("Published CreditApplicationCreated for {CreditId}", id); + + return credit; + } +} diff --git a/CreditApp.Domain/CreditApp.Domain.csproj b/CreditApp.Domain/CreditApp.Domain.csproj new file mode 100644 index 00000000..1d2bd2cb --- /dev/null +++ b/CreditApp.Domain/CreditApp.Domain.csproj @@ -0,0 +1,11 @@ + + + + net8.0 + enable + enable + true + $(NoWarn);1591 + + + diff --git a/CreditApp.Domain/Dictionaries/CreditDictionaries.cs b/CreditApp.Domain/Dictionaries/CreditDictionaries.cs new file mode 100644 index 00000000..4c11577c --- /dev/null +++ b/CreditApp.Domain/Dictionaries/CreditDictionaries.cs @@ -0,0 +1,39 @@ +namespace CreditApp.Domain.Dictionaries; + +/// +/// Статический справочник типов кредитов и статусов заявок. +/// Содержит массивы доступных типов кредитов и статусов, а также утилиту для проверки терминального статуса. +/// +public static class CreditDictionaries +{ + /// + /// Доступные типы кредитов. + /// Порядок и значения используются в пользовательском интерфейсе и бизнес-логике приложения. + /// + public static readonly string[] CreditTypes = + [ + "Потребительский", + "Ипотека", + "Автокредит" + ]; + + /// + /// Возможные статусы кредитной заявки. + /// Последние два статуса считаются терминальными (завершёнными). + /// + public static readonly string[] Statuses = + [ + "Новая", + "В обработке", + "Одобрена", + "Отклонена" + ]; + + /// + /// Определяет, является ли указанный статус терминальным (завершённым). + /// + /// Строковое представление статуса заявки. + /// True, если статус равен "Одобрена" или "Отклонена". + public static bool IsTerminal(string status) + => status is "Одобрена" or "Отклонена"; +} diff --git a/CreditApp.Domain/Entities/CreditApplication.cs b/CreditApp.Domain/Entities/CreditApplication.cs new file mode 100644 index 00000000..699f3e44 --- /dev/null +++ b/CreditApp.Domain/Entities/CreditApplication.cs @@ -0,0 +1,48 @@ +namespace CreditApp.Domain.Entities; + +/// +/// Кредитная заявка +/// +public class CreditApplication +{ + /// + /// Идентификатор в системе + /// + public int Id { get; set; } + /// + /// Тип кредита + /// + public required string CreditType { get; init; } + /// + /// Запрашиваемая сумма + /// + public decimal RequestedAmount { get; init; } + /// + /// Срок в месяцах + /// + public int TermMonths { get; init; } + /// + /// Процентная ставка + /// + public double InterestRate { get; init; } + /// + /// Дата подачи + /// + public DateOnly SubmissionDate { get; init; } + /// + /// Необходимость страховки + /// + public bool HasInsurance { get; init; } + /// + /// Статус заявки + /// + public required string Status { get; init; } + /// + /// Дата решения + /// + public DateOnly? DecisionDate { get; init; } + /// + /// Одобренная сумма + /// + public decimal? ApprovedAmount { get; init; } +} diff --git a/CreditApp.FileService/Consumers/CreditApplicationCreatedConsumer.cs b/CreditApp.FileService/Consumers/CreditApplicationCreatedConsumer.cs new file mode 100644 index 00000000..e0ac71c2 --- /dev/null +++ b/CreditApp.FileService/Consumers/CreditApplicationCreatedConsumer.cs @@ -0,0 +1,34 @@ +using System.Text.Json; +using CreditApp.Application.Messages; +using CreditApp.FileService.Services; +using MassTransit; + +namespace CreditApp.FileService.Consumers; + +/// +/// Потребитель сообщений о создании кредитных заявок. +/// Получает сообщения из SQS-очереди (подписанной на SNS-топик), сериализует заявку в JSON +/// и сохраняет файл в объектное хранилище S3. +/// +/// Сервис файлового хранилища S3. +/// Логгер для записи событий. +public class CreditApplicationCreatedConsumer( + IS3FileStorage fileStorage, + ILogger logger) : IConsumer +{ + /// + /// Обрабатывает входящее сообщение: сериализует кредитную заявку в JSON и загружает в S3. + /// + /// Контекст сообщения MassTransit. + public async Task Consume(ConsumeContext context) + { + var application = context.Message.Application; + var key = $"credit-applications/{application.Id}_{DateTime.UtcNow:yyyyMMdd_HHmmss}.json"; + + var json = JsonSerializer.Serialize(application); + + await fileStorage.UploadAsync(key, json, context.CancellationToken); + + logger.LogInformation("Saved credit application {Id} to S3 as {Key}", application.Id, key); + } +} diff --git a/CreditApp.FileService/CreditApp.FileService.csproj b/CreditApp.FileService/CreditApp.FileService.csproj new file mode 100644 index 00000000..1d339a81 --- /dev/null +++ b/CreditApp.FileService/CreditApp.FileService.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/CreditApp.FileService/Program.cs b/CreditApp.FileService/Program.cs new file mode 100644 index 00000000..1495f079 --- /dev/null +++ b/CreditApp.FileService/Program.cs @@ -0,0 +1,50 @@ +using Amazon.S3; +using Amazon.SimpleNotificationService; +using Amazon.SQS; +using CreditApp.FileService.Consumers; +using CreditApp.FileService.Services; +using CreditApp.ServiceDefaults; +using MassTransit; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +var awsServiceUrl = builder.Configuration["Aws:ServiceUrl"] ?? "http://localhost:4566"; +var awsRegion = builder.Configuration["Aws:Region"] ?? "us-east-1"; +var awsAccessKey = builder.Configuration["Aws:AccessKey"] ?? "test"; +var awsSecretKey = builder.Configuration["Aws:SecretKey"] ?? "test"; + +builder.Services.AddSingleton(_ => new AmazonS3Client( + awsAccessKey, awsSecretKey, + new AmazonS3Config + { + ServiceURL = awsServiceUrl, + ForcePathStyle = true + })); + +builder.Services.AddSingleton(); + +builder.Services.AddMassTransit(x => +{ + x.AddConsumer(); + + x.UsingAmazonSqs((context, cfg) => + { + cfg.Host(awsRegion, h => + { + h.Config(new AmazonSQSConfig { ServiceURL = awsServiceUrl }); + h.Config(new AmazonSimpleNotificationServiceConfig { ServiceURL = awsServiceUrl }); + h.AccessKey(awsAccessKey); + h.SecretKey(awsSecretKey); + }); + + cfg.ConfigureEndpoints(context); + }); +}); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +app.Run(); diff --git a/CreditApp.FileService/Properties/launchSettings.json b/CreditApp.FileService/Properties/launchSettings.json new file mode 100644 index 00000000..27e382b8 --- /dev/null +++ b/CreditApp.FileService/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:51953", + "sslPort": 44307 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5098", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7121;http://localhost:5098", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CreditApp.FileService/Services/IS3FileStorage.cs b/CreditApp.FileService/Services/IS3FileStorage.cs new file mode 100644 index 00000000..0302d676 --- /dev/null +++ b/CreditApp.FileService/Services/IS3FileStorage.cs @@ -0,0 +1,16 @@ +namespace CreditApp.FileService.Services; + +/// +/// Сервис для работы с файловым хранилищем S3. +/// Предоставляет операции загрузки и скачивания файлов из объектного хранилища. +/// +public interface IS3FileStorage +{ + /// + /// Загружает содержимое в S3 по указанному ключу. + /// + /// Ключ (путь) файла в бакете. + /// Текстовое содержимое файла. + /// Токен отмены. + public Task UploadAsync(string key, string content, CancellationToken ct = default); +} diff --git a/CreditApp.FileService/Services/S3FileStorage.cs b/CreditApp.FileService/Services/S3FileStorage.cs new file mode 100644 index 00000000..8d050cdc --- /dev/null +++ b/CreditApp.FileService/Services/S3FileStorage.cs @@ -0,0 +1,48 @@ +using Amazon.S3; +using Amazon.S3.Model; + +namespace CreditApp.FileService.Services; + +/// +/// Реализация файлового хранилища на базе Amazon S3. +/// Обеспечивает загрузку JSON-файлов в указанный бакет. +/// +/// Клиент Amazon S3. +/// Конфигурация приложения для получения имени бакета. +/// Логгер для записи событий. +public class S3FileStorage(IAmazonS3 s3Client, IConfiguration configuration, ILogger logger) : IS3FileStorage +{ + private readonly string _bucketName = configuration["Aws:BucketName"] ?? "credit-files"; + + /// + public async Task UploadAsync(string key, string content, CancellationToken ct = default) + { + await EnsureBucketExistsAsync(); + + var request = new PutObjectRequest + { + BucketName = _bucketName, + Key = key, + ContentBody = content, + ContentType = "application/json" + }; + + await s3Client.PutObjectAsync(request, ct); + logger.LogInformation("Uploaded file {Key} to bucket {Bucket}", key, _bucketName); + } + + /// + /// Проверяет существование бакета и создаёт его при необходимости. + /// + private async Task EnsureBucketExistsAsync() + { + try + { + await s3Client.EnsureBucketExistsAsync(_bucketName); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to ensure bucket {Bucket} exists", _bucketName); + } + } +} diff --git a/CreditApp.FileService/appsettings.Development.json b/CreditApp.FileService/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CreditApp.FileService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CreditApp.FileService/appsettings.json b/CreditApp.FileService/appsettings.json new file mode 100644 index 00000000..d8b72b21 --- /dev/null +++ b/CreditApp.FileService/appsettings.json @@ -0,0 +1,16 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Aws": { + "ServiceUrl": "http://localhost:4566", + "Region": "us-east-1", + "AccessKey": "test", + "SecretKey": "test", + "BucketName": "credit-files" + } +} diff --git a/CreditApp.Gateway/CreditApp.Gateway.csproj b/CreditApp.Gateway/CreditApp.Gateway.csproj new file mode 100644 index 00000000..aefd36bc --- /dev/null +++ b/CreditApp.Gateway/CreditApp.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/CreditApp.Gateway/Extensions/AspireServiceDiscoveryExtensions.cs b/CreditApp.Gateway/Extensions/AspireServiceDiscoveryExtensions.cs new file mode 100644 index 00000000..75c7000b --- /dev/null +++ b/CreditApp.Gateway/Extensions/AspireServiceDiscoveryExtensions.cs @@ -0,0 +1,65 @@ +namespace CreditApp.Gateway.Extensions; + +/// +/// Расширения для интеграции Aspire service discovery с Ocelot. +/// Динамически разрешает адреса downstream-сервисов из переменных окружения Aspire +/// и переопределяет маршруты Ocelot через in-memory конфигурацию. +/// +public static class AspireServiceDiscoveryExtensions +{ + /// + /// Разрешает адреса downstream-сервисов из Aspire service discovery + /// и переопределяет конфигурацию Ocelot. + /// + /// WebApplicationBuilder с загруженной конфигурацией. + /// + /// Маппинг host:port → имя сервиса для привязки весов в балансировщике. + /// + public static Dictionary ResolveDownstreamServices(this WebApplicationBuilder builder) + { + var generatorNames = builder.Configuration + .GetSection("GeneratorServices") + .Get() ?? []; + + var addressOverrides = new List>(); + var hostPortToServiceName = new Dictionary(); + var schemeResolved = false; + + for (var i = 0; i < generatorNames.Length; i++) + { + var name = generatorNames[i]; + + var url = builder.Configuration[$"services:{name}:http:0"] + ?? builder.Configuration[$"services:{name}:https:0"]; + + string resolvedHost, resolvedPort; + + if (!string.IsNullOrEmpty(url) && Uri.TryCreate(url, UriKind.Absolute, out var uri)) + { + resolvedHost = uri.Host; + resolvedPort = uri.Port.ToString(); + + addressOverrides.Add(new($"Routes:0:DownstreamHostAndPorts:{i}:Host", resolvedHost)); + addressOverrides.Add(new($"Routes:0:DownstreamHostAndPorts:{i}:Port", resolvedPort)); + + if (!schemeResolved) + { + addressOverrides.Add(new($"Routes:0:DownstreamScheme", uri.Scheme)); + schemeResolved = true; + } + } + else + { + resolvedHost = builder.Configuration[$"Routes:0:DownstreamHostAndPorts:{i}:Host"] ?? "localhost"; + resolvedPort = builder.Configuration[$"Routes:0:DownstreamHostAndPorts:{i}:Port"] ?? "0"; + } + + hostPortToServiceName[$"{resolvedHost}:{resolvedPort}"] = name; + } + + if (addressOverrides.Count > 0) + builder.Configuration.AddInMemoryCollection(addressOverrides); + + return hostPortToServiceName; + } +} diff --git a/CreditApp.Gateway/LoadBalancing/WeightedRoundRobinBalancer.cs b/CreditApp.Gateway/LoadBalancing/WeightedRoundRobinBalancer.cs new file mode 100644 index 00000000..a48b1b10 --- /dev/null +++ b/CreditApp.Gateway/LoadBalancing/WeightedRoundRobinBalancer.cs @@ -0,0 +1,94 @@ +using Ocelot.LoadBalancer.Errors; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Values; + +namespace CreditApp.Gateway.LoadBalancing; + +/// +/// Кастомный балансировщик нагрузки, реализующий алгоритм Weighted Round Robin. +/// Каждый downstream-хост получает количество запросов, пропорциональное его весу. +/// Веса привязаны к именам сервисов через маппинг hostPort → serviceName. +/// +public class WeightedRoundRobinBalancer( + IServiceDiscoveryProvider serviceDiscoveryProvider, + Dictionary replicaWeights, + Dictionary hostPortToServiceName) : ILoadBalancer +{ + private readonly (List<(ServiceHostAndPort Host, int Weight)> Services, int TotalWeight) _config = + BuildWeightedList(serviceDiscoveryProvider, replicaWeights, hostPortToServiceName); + + private int _currentIndex = -1; + private readonly object _lock = new(); + + public string Type => nameof(WeightedRoundRobinBalancer); + + /// + /// Строит развёрнутый список хостов: хост с весом 3 появляется 3 раза. + /// + private static (List<(ServiceHostAndPort Host, int Weight)> Services, int TotalWeight) BuildWeightedList( + IServiceDiscoveryProvider provider, + Dictionary replicaWeights, + Dictionary hostPortToServiceName) + { + var services = provider.GetAsync().Result; + var list = new List<(ServiceHostAndPort Host, int Weight)>(); + var totalWeight = 0; + + foreach (var service in services) + { + var key = $"{service.HostAndPort.DownstreamHost}:{service.HostAndPort.DownstreamPort}"; + var weight = 1; + + if (hostPortToServiceName.TryGetValue(key, out var serviceName) + && replicaWeights.TryGetValue(serviceName, out var configuredWeight)) + { + weight = configuredWeight; + } + + list.Add((service.HostAndPort, weight)); + totalWeight += weight; + } + + return (list, totalWeight); + } + + /// + /// Выбирает следующий хост по алгоритму Weighted Round Robin. + /// + public Task> LeaseAsync(HttpContext httpContext) + { + if (_config.Services.Count == 0) + { + return Task.FromResult>( + new ErrorResponse(new ServicesAreEmptyError("Generator services list is empty, no hosts were discovered"))); + } + + lock (_lock) + { + _currentIndex = (_currentIndex + 1) % _config.TotalWeight; + + var cumulative = 0; + + foreach (var (host, weight) in _config.Services) + { + cumulative += weight; + if (_currentIndex < cumulative) + { + var key = $"{host.DownstreamHost}:{host.DownstreamPort}"; + var serviceName = hostPortToServiceName.GetValueOrDefault(key, key); + httpContext.Items["SelectedService"] = serviceName; + + return Task.FromResult>( + new OkResponse(host)); + } + } + + return Task.FromResult>( + new ErrorResponse(new ServicesAreEmptyError("Could not match any service host within cumulative weight bounds"))); + } + } + + public void Release(ServiceHostAndPort hostAndPort) { } +} diff --git a/CreditApp.Gateway/Program.cs b/CreditApp.Gateway/Program.cs new file mode 100644 index 00000000..e52b6662 --- /dev/null +++ b/CreditApp.Gateway/Program.cs @@ -0,0 +1,46 @@ +using CreditApp.Gateway.Extensions; +using CreditApp.Gateway.LoadBalancing; +using CreditApp.ServiceDefaults; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); + +var hostPortToServiceName = builder.ResolveDownstreamServices(); + +var replicaWeights = builder.Configuration + .GetSection("ReplicaWeights") + .Get>() ?? []; + +builder.Services + .AddOcelot(builder.Configuration) + .AddCustomLoadBalancer((route, serviceDiscovery) => + new WeightedRoundRobinBalancer(serviceDiscovery, replicaWeights, hostPortToServiceName)); + +var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get() ?? []; + +builder.Services.AddCors(options => +{ + options.AddPolicy("GatewayCors", policy => + { + policy.AllowAnyHeader().AllowAnyMethod(); + + if (builder.Environment.IsDevelopment()) + policy.AllowAnyOrigin(); + else + policy.WithOrigins(allowedOrigins); + }); +}); + +var app = builder.Build(); + +app.UseCors("GatewayCors"); +app.MapDefaultEndpoints(); + +await app.UseOcelot(); + +app.Run(); diff --git a/CreditApp.Gateway/Properties/launchSettings.json b/CreditApp.Gateway/Properties/launchSettings.json new file mode 100644 index 00000000..3b614284 --- /dev/null +++ b/CreditApp.Gateway/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:60672", + "sslPort": 44348 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5096", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7040;http://localhost:5096", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CreditApp.Gateway/appsettings.Development.json b/CreditApp.Gateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CreditApp.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CreditApp.Gateway/appsettings.json b/CreditApp.Gateway/appsettings.json new file mode 100644 index 00000000..cb4951dc --- /dev/null +++ b/CreditApp.Gateway/appsettings.json @@ -0,0 +1,18 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "GeneratorServices": [ "credit-api-1", "credit-api-2", "credit-api-3" ], + "ReplicaWeights": { + "credit-api-1": 3, + "credit-api-2": 2, + "credit-api-3": 1 + }, + "Cors": { + "AllowedOrigins": [ "https://localhost:7282" ] + } +} diff --git a/CreditApp.Gateway/ocelot.json b/CreditApp.Gateway/ocelot.json new file mode 100644 index 00000000..296bf46e --- /dev/null +++ b/CreditApp.Gateway/ocelot.json @@ -0,0 +1,21 @@ +{ + "Routes": [ + { + "DownstreamPathTemplate": "/api/Credit", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { "Host": "localhost", "Port": 7001 }, + { "Host": "localhost", "Port": 7002 }, + { "Host": "localhost", "Port": 7003 } + ], + "UpstreamPathTemplate": "/api/Credit", + "UpstreamHttpMethod": [ "GET" ], + "LoadBalancerOptions": { + "Type": "WeightedRoundRobinBalancer" + } + } + ], + "GlobalConfiguration": { + "BaseUrl": "https://localhost:7201" + } +} diff --git a/CreditApp.Infrastructure/CreditApp.Infrastructure.csproj b/CreditApp.Infrastructure/CreditApp.Infrastructure.csproj new file mode 100644 index 00000000..395531f8 --- /dev/null +++ b/CreditApp.Infrastructure/CreditApp.Infrastructure.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/CreditApp.Infrastructure/Generators/CreditApplicationGenerator.cs b/CreditApp.Infrastructure/Generators/CreditApplicationGenerator.cs new file mode 100644 index 00000000..36c7a321 --- /dev/null +++ b/CreditApp.Infrastructure/Generators/CreditApplicationGenerator.cs @@ -0,0 +1,39 @@ +using Bogus; +using CreditApp.Application.Interfaces; +using CreditApp.Domain.Dictionaries; +using CreditApp.Domain.Entities; +using Microsoft.Extensions.Configuration; + +namespace CreditApp.Infrastructure.Generators; + +public class CreditApplicationGenerator : ICreditApplicationGenerator +{ + private readonly Faker _faker; + + public CreditApplicationGenerator(IConfiguration configuration) + { + var centralBankRate = configuration.GetValue("CreditGenerator:CentralBankRate", 16.0); + + _faker = new Faker() + .RuleFor(c => c.CreditType, f => f.PickRandom(CreditDictionaries.CreditTypes)) + .RuleFor(c => c.RequestedAmount, f => Math.Round(f.Random.Decimal(100_000, 10_000_000), 2)) + .RuleFor(c => c.TermMonths, f => f.Random.Int(6, 360)) + .RuleFor(c => c.InterestRate, f => Math.Round(f.Random.Double(centralBankRate, centralBankRate + 10), 2)) + .RuleFor(c => c.SubmissionDate, f => DateOnly.FromDateTime(f.Date.Between(DateTime.Now.AddYears(-2), DateTime.Now))) + .RuleFor(c => c.HasInsurance, f => f.Random.Bool()) + .RuleFor(c => c.Status, f => f.PickRandom(CreditDictionaries.Statuses)) + .RuleFor(c => c.DecisionDate, (f, c) => CreditDictionaries.IsTerminal(c.Status) + ? c.SubmissionDate.AddDays(f.Random.Int(1, 30)) + : null) + .RuleFor(c => c.ApprovedAmount, (f, c) => c.Status == "Одобрена" + ? Math.Round(f.Random.Decimal(10_000, c.RequestedAmount), 2) + : null); + } + + public Task GenerateAsync(int id) + { + var application = _faker.Generate(); + application.Id = id; + return Task.FromResult(application); + } +} diff --git a/CreditApp.IntegrationTests/AppHostFixture.cs b/CreditApp.IntegrationTests/AppHostFixture.cs new file mode 100644 index 00000000..e1e4b395 --- /dev/null +++ b/CreditApp.IntegrationTests/AppHostFixture.cs @@ -0,0 +1,80 @@ +using Amazon.S3; +using Amazon.S3.Model; +using Aspire.Hosting; +using Aspire.Hosting.Testing; +using Microsoft.Extensions.DependencyInjection; + +namespace CreditApp.IntegrationTests; + +/// +/// Фикстура для поднятия Aspire AppHost один раз на все тесты. +/// +public class AppHostFixture : IAsyncLifetime +{ + public DistributedApplication App { get; private set; } = null!; + public AmazonS3Client S3Client { get; private set; } = null!; + + public async Task InitializeAsync() + { + var appHost = await DistributedApplicationTestingBuilder + .CreateAsync(); + + appHost.Services.ConfigureHttpClientDefaults(http => + http.AddStandardResilienceHandler(options => + { + options.TotalRequestTimeout.Timeout = TimeSpan.FromMinutes(3); + options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(60); + options.CircuitBreaker.SamplingDuration = TimeSpan.FromMinutes(3); + options.Retry.MaxRetryAttempts = 10; + options.Retry.Delay = TimeSpan.FromSeconds(3); + })); + + App = await appHost.BuildAsync(); + await App.StartAsync(); + + await App.ResourceNotifications + .WaitForResourceHealthyAsync("creditapp-gateway") + .WaitAsync(TimeSpan.FromMinutes(3)); + + var localStackUrl = App.GetEndpoint("localstack", "localstack").ToString().TrimEnd('/'); + S3Client = new AmazonS3Client("test", "test", new AmazonS3Config + { + ServiceURL = localStackUrl, + ForcePathStyle = true + }); + } + + /// + /// Ожидает появления файла в S3 с указанным префиксом. + /// + public async Task> WaitForS3ObjectAsync(string prefix, int maxAttempts = 15) + { + for (var i = 0; i < maxAttempts; i++) + { + await Task.Delay(TimeSpan.FromSeconds(2)); + + var listResponse = await S3Client.ListObjectsV2Async(new ListObjectsV2Request + { + BucketName = "credit-files", + Prefix = prefix + }); + + if (listResponse.S3Objects.Count > 0) + return listResponse.S3Objects; + } + + return []; + } + + public async Task DisposeAsync() + { + S3Client.Dispose(); + + try + { + await App.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(30)); + } + catch (TimeoutException) { } + catch (OperationCanceledException) { } + } +} diff --git a/CreditApp.IntegrationTests/CreditApp.IntegrationTests.csproj b/CreditApp.IntegrationTests/CreditApp.IntegrationTests.csproj new file mode 100644 index 00000000..7700b3b2 --- /dev/null +++ b/CreditApp.IntegrationTests/CreditApp.IntegrationTests.csproj @@ -0,0 +1,36 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CreditApp.IntegrationTests/CreditIntegrationTests.cs b/CreditApp.IntegrationTests/CreditIntegrationTests.cs new file mode 100644 index 00000000..b4f29117 --- /dev/null +++ b/CreditApp.IntegrationTests/CreditIntegrationTests.cs @@ -0,0 +1,214 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Amazon.S3.Model; +using Aspire.Hosting.Testing; +using CreditApp.Domain.Entities; + +namespace CreditApp.IntegrationTests; + +/// +/// Интеграционные тесты для проверки корректной работы всех сервисов бекенда. +/// +public class CreditIntegrationTests(AppHostFixture fixture) : IClassFixture +{ + private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + + /// + /// Проверяет, что API отвечает на health check. + /// + [Fact] + public async Task Api_HealthCheck_ReturnsHealthy() + { + using var httpClient = fixture.App.CreateHttpClient("credit-api-1"); + using var response = await httpClient.GetAsync("/health"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Проверяет, что FileService отвечает на health check. + /// + [Fact] + public async Task FileService_HealthCheck_ReturnsHealthy() + { + using var httpClient = fixture.App.CreateHttpClient("creditapp-fileservice"); + using var response = await httpClient.GetAsync("/health"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Проверяет, что запрос через Gateway возвращает корректную кредитную заявку. + /// + [Fact] + public async Task Gateway_GetCredit_ReturnsValidCreditApplication() + { + using var httpClient = fixture.App.CreateHttpClient("creditapp-gateway", "https"); + using var response = await httpClient.GetAsync("/api/Credit?id=1"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var credit = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(credit); + Assert.Equal(1, credit.Id); + Assert.False(string.IsNullOrEmpty(credit.CreditType)); + Assert.True(credit.RequestedAmount > 0); + Assert.True(credit.TermMonths > 0); + Assert.True(credit.InterestRate > 0); + } + + /// + /// Проверяет, что повторный запрос возвращает закэшированные данные из Redis. + /// + [Fact] + public async Task Gateway_RepeatedRequests_ReturnsCachedData() + { + var testId = Random.Shared.Next(1, 100000); + using var httpClient = fixture.App.CreateHttpClient("creditapp-gateway", "https"); + + using var response1 = await httpClient.GetAsync($"/api/Credit?id={testId}"); + response1.EnsureSuccessStatusCode(); + var content1 = await response1.Content.ReadAsStringAsync(); + + using var response2 = await httpClient.GetAsync($"/api/Credit?id={testId}"); + response2.EnsureSuccessStatusCode(); + var content2 = await response2.Content.ReadAsStringAsync(); + + Assert.Equal(content1, content2); + } + + /// + /// Проверяет маршрутизацию Gateway к API-репликам. + /// + [Fact] + public async Task Gateway_MultipleRequests_AllSucceed() + { + using var httpClient = fixture.App.CreateHttpClient("creditapp-gateway", "https"); + + var tasks = Enumerable.Range(1, 6) + .Select(i => httpClient.GetAsync($"/api/Credit?id={i + 300}")); + + var responses = await Task.WhenAll(tasks); + + Assert.All(responses, r => Assert.Equal(HttpStatusCode.OK, r.StatusCode)); + } + + /// + /// Проверяет сквозной сценарий: Gateway → API → SNS → FileService → S3. + /// + [Fact] + public async Task GetCredit_FileServiceSavesToS3() + { + var id = Random.Shared.Next(100000, 200000); + + using var httpClient = fixture.App.CreateHttpClient("creditapp-gateway", "https"); + using var response = await httpClient.GetAsync($"/api/Credit?id={id}"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var objects = await fixture.WaitForS3ObjectAsync($"credit-applications/{id}_"); + + Assert.NotEmpty(objects); + + var getResponse = await fixture.S3Client.GetObjectAsync("credit-files", objects.First().Key); + using var reader = new StreamReader(getResponse.ResponseStream); + var json = await reader.ReadToEndAsync(); + var savedCredit = JsonSerializer.Deserialize(json, _jsonOptions); + + Assert.NotNull(savedCredit); + Assert.Equal(id, savedCredit.Id); + } + + /// + /// Проверяет, что разные id возвращают разные кредитные заявки. + /// + [Fact] + public async Task Gateway_DifferentIds_ReturnDifferentApplications() + { + using var httpClient = fixture.App.CreateHttpClient("creditapp-gateway", "https"); + + var credit1 = await httpClient.GetFromJsonAsync("/api/Credit?id=501", _jsonOptions); + var credit2 = await httpClient.GetFromJsonAsync("/api/Credit?id=502", _jsonOptions); + + Assert.NotNull(credit1); + Assert.NotNull(credit2); + Assert.Equal(501, credit1.Id); + Assert.Equal(502, credit2.Id); + } + + /// + /// Проверяет, что все обязательные поля заявки заполнены корректно. + /// + [Fact] + public async Task Gateway_GetCredit_AllFieldsPopulated() + { + var id = Random.Shared.Next(200000, 300000); + using var httpClient = fixture.App.CreateHttpClient("creditapp-gateway", "https"); + + var credit = await httpClient.GetFromJsonAsync($"/api/Credit?id={id}", _jsonOptions); + + Assert.NotNull(credit); + Assert.Equal(id, credit.Id); + Assert.False(string.IsNullOrEmpty(credit.CreditType)); + Assert.False(string.IsNullOrEmpty(credit.Status)); + Assert.True(credit.RequestedAmount > 0); + Assert.True(credit.TermMonths > 0); + Assert.True(credit.InterestRate > 0); + Assert.NotEqual(default, credit.SubmissionDate); + } + + /// + /// Проверяет, что файл в S3 содержит все поля кредитной заявки. + /// + [Fact] + public async Task GetCredit_S3FileContainsAllFields() + { + var id = Random.Shared.Next(300000, 400000); + + using var httpClient = fixture.App.CreateHttpClient("creditapp-gateway", "https"); + var originalCredit = await httpClient.GetFromJsonAsync($"/api/Credit?id={id}", _jsonOptions); + Assert.NotNull(originalCredit); + + var objects = await fixture.WaitForS3ObjectAsync($"credit-applications/{id}_"); + Assert.NotEmpty(objects); + + var getResponse = await fixture.S3Client.GetObjectAsync("credit-files", objects.First().Key); + using var reader = new StreamReader(getResponse.ResponseStream); + var json = await reader.ReadToEndAsync(); + var savedCredit = JsonSerializer.Deserialize(json, _jsonOptions); + + Assert.NotNull(savedCredit); + Assert.Equal(originalCredit.Id, savedCredit.Id); + Assert.Equal(originalCredit.CreditType, savedCredit.CreditType); + Assert.Equal(originalCredit.RequestedAmount, savedCredit.RequestedAmount); + Assert.Equal(originalCredit.TermMonths, savedCredit.TermMonths); + Assert.Equal(originalCredit.InterestRate, savedCredit.InterestRate); + Assert.Equal(originalCredit.Status, savedCredit.Status); + } + + /// + /// Проверяет, что повторный запрос (cache hit) не создаёт дубликат файла в S3. + /// + [Fact] + public async Task GetCredit_CacheHit_DoesNotDuplicateS3File() + { + var id = Random.Shared.Next(400000, 500000); + + using var httpClient = fixture.App.CreateHttpClient("creditapp-gateway", "https"); + + await httpClient.GetAsync($"/api/Credit?id={id}"); + var objectsAfterFirst = await fixture.WaitForS3ObjectAsync($"credit-applications/{id}_"); + Assert.NotEmpty(objectsAfterFirst); + + await httpClient.GetAsync($"/api/Credit?id={id}"); + await Task.Delay(TimeSpan.FromSeconds(5)); + + var listResponse = await fixture.S3Client.ListObjectsV2Async(new ListObjectsV2Request + { + BucketName = "credit-files", + Prefix = $"credit-applications/{id}_" + }); + + Assert.Single(listResponse.S3Objects); + } +} diff --git a/CreditApp.IntegrationTests/xunit.runner.json b/CreditApp.IntegrationTests/xunit.runner.json new file mode 100644 index 00000000..29d3d476 --- /dev/null +++ b/CreditApp.IntegrationTests/xunit.runner.json @@ -0,0 +1,5 @@ +{ + "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json", + "diagnosticMessages": true, + "maxParallelThreads": 1 +} diff --git a/CreditApp/CreditApp.AppHost/AppHost.cs b/CreditApp/CreditApp.AppHost/AppHost.cs new file mode 100644 index 00000000..0a6d40cd --- /dev/null +++ b/CreditApp/CreditApp.AppHost/AppHost.cs @@ -0,0 +1,57 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("credit-cache") + .WithRedisInsight(containerName: "credit-redis-insight"); + +var localstack = builder.AddContainer("localstack", "localstack/localstack") + .WithEndpoint(port: 4566, targetPort: 4566, name: "localstack", scheme: "http") + .WithEnvironment("SERVICES", "s3,sns,sqs") + .WithEnvironment("DEFAULT_REGION", "us-east-1") + .WithEnvironment("AWS_DEFAULT_REGION", "us-east-1") + .WithHttpHealthCheck(path: "/_localstack/health", endpointName: "localstack"); + +var replicaPorts = new Dictionary +{ + ["credit-api-1"] = (7001, 7081), + ["credit-api-2"] = (7002, 7082), + ["credit-api-3"] = (7003, 7083), +}; + +var fileService = builder.AddProject("creditapp-fileservice") + .WithReference(localstack.GetEndpoint("localstack")) + .WaitFor(localstack) + .WithEnvironment("Aws__ServiceUrl", localstack.GetEndpoint("localstack")); + +var apiReplicas = new List>(); + +foreach (var (name, (httpPort, httpsPort)) in replicaPorts) +{ + var replica = builder.AddProject(name) + .WithEndpoint("http", endpoint => endpoint.Port = httpPort) + .WithEndpoint("https", endpoint => endpoint.Port = httpsPort) + .WithReference(redis) + .WaitFor(redis) + .WithReference(localstack.GetEndpoint("localstack")) + .WaitFor(localstack) + .WaitFor(fileService) + .WithEnvironment("Aws__ServiceUrl", localstack.GetEndpoint("localstack")); + + apiReplicas.Add(replica); +} + +var gateway = builder.AddProject("creditapp-gateway") + .WithEndpoint("http", endpoint => endpoint.Port = 7200) + .WithEndpoint("https", endpoint => endpoint.Port = 7201) + .WithExternalHttpEndpoints(); + +foreach (var replica in apiReplicas) +{ + gateway.WithReference(replica) + .WaitFor(replica); +} + +builder.AddProject("client") + .WithReference(gateway) + .WaitFor(gateway); + +builder.Build().Run(); diff --git a/CreditApp/CreditApp.AppHost/CreditApp.AppHost.csproj b/CreditApp/CreditApp.AppHost/CreditApp.AppHost.csproj new file mode 100644 index 00000000..a06c5a6a --- /dev/null +++ b/CreditApp/CreditApp.AppHost/CreditApp.AppHost.csproj @@ -0,0 +1,25 @@ + + + + + + Exe + net8.0 + enable + enable + 70c1c02b-8ca4-435d-8e0e-594485960c89 + + + + + + + + + + + + + + + diff --git a/CreditApp/CreditApp.AppHost/Properties/launchSettings.json b/CreditApp/CreditApp.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..171fa4fd --- /dev/null +++ b/CreditApp/CreditApp.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:17005;http://localhost:15107", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21196", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22132" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15107", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19106", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20243" + } + } + } +} diff --git a/CreditApp/CreditApp.AppHost/appsettings.Development.json b/CreditApp/CreditApp.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CreditApp/CreditApp.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CreditApp/CreditApp.AppHost/appsettings.json b/CreditApp/CreditApp.AppHost/appsettings.json new file mode 100644 index 00000000..31c092aa --- /dev/null +++ b/CreditApp/CreditApp.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CreditApp/CreditApp.ServiceDefaults/CreditApp.ServiceDefaults.csproj b/CreditApp/CreditApp.ServiceDefaults/CreditApp.ServiceDefaults.csproj new file mode 100644 index 00000000..1b6e209a --- /dev/null +++ b/CreditApp/CreditApp.ServiceDefaults/CreditApp.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/CreditApp/CreditApp.ServiceDefaults/Extensions.cs b/CreditApp/CreditApp.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..c5724030 --- /dev/null +++ b/CreditApp/CreditApp.ServiceDefaults/Extensions.cs @@ -0,0 +1,128 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.ServiceDiscovery; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace CreditApp.ServiceDefaults; + +// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// This project should be referenced by each service project in your solution. +// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults +public static class Extensions +{ + private const string HealthEndpointPath = "/health"; + private const string AlivenessEndpointPath = "/alive"; + + public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.ConfigureOpenTelemetry(); + + builder.AddDefaultHealthChecks(); + + builder.Services.AddServiceDiscovery(); + + builder.Services.ConfigureHttpClientDefaults(http => + { + // Turn on resilience by default + http.AddStandardResilienceHandler(); + + // Turn on service discovery by default + http.AddServiceDiscovery(); + }); + + // Uncomment the following to restrict the allowed schemes for service discovery. + // builder.Services.Configure(options => + // { + // options.AllowedSchemes = ["https"]; + // }); + + return builder; + } + + public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddSource(builder.Environment.ApplicationName) + .AddAspNetCoreInstrumentation(tracing => + // Exclude health check requests from tracing + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) + //.AddGrpcClientInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package) + //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"])) + //{ + // builder.Services.AddOpenTelemetry() + // .UseAzureMonitor(); + //} + + return builder; + } + + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Services.AddHealthChecks() + // Add a default liveness check to ensure app is responsive + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + // Adding health checks endpoints to applications in non-development environments has security implications. + // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments. + if (app.Environment.IsDevelopment()) + { + // All health checks must pass for app to be considered ready to accept traffic after starting + app.MapHealthChecks(HealthEndpointPath); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 00000000..a3895d36 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,6 @@ + + + + 9.5.2 + + \ No newline at end of file diff --git a/README.md b/README.md index dcaa5eb7..0b23736e 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,57 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing) +# Лабораторная работа №3 -## Задание -### Цель -Реализация проекта микросервисного бекенда. +## «Объектное хранилище и брокер сообщений» -### Задачи -* Реализация межсервисной коммуникации, -* Изучение работы с брокерами сообщений, -* Изучение архитектурных паттернов, -* Изучение работы со средствами оркестрации на примере .NET Aspire, -* Повторение основ работы с системами контроля версий, -* Интеграционное тестирование. +## Что было сделано -### Лабораторные работы -
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов -
- -В рамках первой лабораторной работы необходимо: -* Реализовать сервис генерации контрактов на основе Bogus, -* Реализовать кеширование при помощи IDistributedCache и Redis, -* Реализовать структурное логирование сервиса генерации, -* Настроить оркестрацию Aspire. - -
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы -
- -В рамках второй лабораторной работы необходимо: -* Настроить оркестрацию на запуск нескольких реплик сервиса генерации, -* Реализовать апи гейтвей на основе Ocelot, -* Имплементировать алгоритм балансировки нагрузки согласно варианту. +В рамках третьей лабораторной работы добавлено объектное хранилище, реализован файловый сервис, настроена асинхронная передача данных через брокер сообщений и написаны интеграционные тесты. -
-
-
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда -
+### 1. Добавлено объектное хранилище (S3 через LocalStack) -В рамках третьей лабораторной работы необходимо: -* Добавить в оркестрацию объектное хранилище, -* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище, -* Реализовать отправку генерируемых данных в файловый сервис посредством брокера, -* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе. +- В оркестрацию AppHost добавлен контейнер LocalStack +- Настроен health check по эндпоинту `/_localstack/health`. +- Регион: `us-east-1`, порт: `4566`. -
-
-
-4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud -
- -В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы: -* Клиент - в хостинг через отдельный бакет Object Storage, -* Сервис генерации - в Cloud Function, -* Апи гейтвей - в Serverless Integration как API Gateway, -* Брокер сообщений - в Message Queue, -* Файловый сервис - в Cloud Function, -* Объектное хранилище - в отдельный бакет Object Storage, +### 2. Реализован файловый сервис (CreditApp.FileService) -
-
+- Сервис принимает сообщения из SQS-очереди через MassTransit consumer (`CreditApplicationCreatedConsumer`). +- Полученные кредитные заявки сериализуются в JSON и сохраняются в S3-бакет `credit-files`. +- Ключ файла: `credit-applications/{id}_{timestamp}.json`. +- Реализован интерфейс `IS3FileStorage` и его реализация `S3FileStorage` с автоматическим созданием бакета. +- AWS-конфигурация (ServiceUrl, Region, AccessKey, SecretKey) вынесена в `appsettings.json`. -## Задание. Общая часть -**Обязательно**: -* Реализация серверной части на [.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 с информацией о задании, скриншоты приложения и прочая информация. +### 3. Реализована отправка данных через брокер сообщений (SNS/SQS) -**Факультативно**: -* Перенос бекенда на облачную инфраструктуру Yandex Cloud +- Брокер сообщений: Amazon SNS (Simple Notification Service) через LocalStack. +- API публикует сообщение `CreditApplicationCreated` в SNS-топик через MassTransit (`IPublishEndpoint`). +- FileService подписан на SNS-топик через SQS-очередь и получает сообщения через MassTransit consumer. +- Сообщение публикуется только при cache miss (генерация новой заявки), что исключает дублирование файлов. +- Цепочка: API → SNS → SQS → FileService Consumer → S3. -Внимательно прочитайте [дискуссии](https://github.com/itsecd/cloud-development/discussions/1) о том, как работает автоматическое распределение на ревью. -Сразу корректно называйте свои pr, чтобы они попали на ревью нужному преподавателю. +### 5. Реализованы интеграционные тесты (CreditApp.IntegrationTests) -По итогу работы в семестре должна получиться следующая информационная система: -
-C4 диаграмма -Современные_технологии_разработки_ПО_drawio -
+Написано 10 тестов, проверяющих корректность работы всех сервисов вместе: -## Варианты заданий -Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи. +- `Api_HealthCheck_ReturnsHealthy` — API отвечает на health check. +- `FileService_HealthCheck_ReturnsHealthy` — FileService отвечает на health check. +- `Gateway_GetCredit_ReturnsValidCreditApplication` — Gateway возвращает корректную заявку. +- `Gateway_RepeatedRequests_ReturnsCachedData` — повторный запрос возвращает данные из Redis-кэша. +- `Gateway_MultipleRequests_AllSucceed` — маршрутизация к API-репликам работает. +- `Gateway_DifferentIds_ReturnDifferentApplications` — разные id возвращают разные заявки. +- `Gateway_GetCredit_AllFieldsPopulated` — все обязательные поля заявки заполнены. +- `GetCredit_FileServiceSavesToS3` — сквозной сценарий: Gateway → API → SNS → FileService → S3. +- `GetCredit_S3FileContainsAllFields` — файл в S3 содержит все поля исходной заявки. +- `GetCredit_CacheHit_DoesNotDuplicateS3File` — cache hit не создаёт дубликат файла в S3. -[Список вариантов](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). +## Используемые технологии +- .NET 8 +- ASP.NET Core Web API +- Ocelot API Gateway +- Blazor WebAssembly +- Bogus +- Redis / IDistributedCache +- MassTransit + Amazon SNS/SQS +- AWS S3 (LocalStack) +- .NET Aspire +- xUnit + Aspire.Hosting.Testing