diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..a470fb50 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №3 "Интеграционное тестирование" + Вариант №43 "Сотрудник компании" + Выполнена Казаковым Андреем 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..cc67cbd9 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7000/api/employee" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..e318f998 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,16 +5,126 @@ 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}") = "CompanyEmployee.AppHost", "CompanyEmployee.AppHost\CompanyEmployee.AppHost.csproj", "{069756DA-EFFA-4835-B69C-0849C48BE473}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.ServiceDefaults", "CompanyEmployee.ServiceDefaults\CompanyEmployee.ServiceDefaults.csproj", "{60C547C0-C951-4270-1D2E-4BB68A5739B6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.Domain", "CompanyEmployee.Domain\CompanyEmployee.Domain.csproj", "{FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.Api", "CompanyEmployee.Api\CompanyEmployee.Api.csproj", "{EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.Gateway", "CompanyEmployee.Gateway\CompanyEmployee.Gateway.csproj", "{73C5B926-EAC3-32E1-1AD5-911888B0E715}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.FileService", "CompanyEmployee.FileService\CompanyEmployee.FileService.csproj", "{A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.IntegrationTests", "CompanyEmployee.IntegrationTests\CompanyEmployee.IntegrationTests.csproj", "{5B3E2130-4B0A-414D-B075-7AF50B7D9B55}" +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 + {069756DA-EFFA-4835-B69C-0849C48BE473}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Debug|Any CPU.Build.0 = Debug|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Debug|x64.ActiveCfg = Debug|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Debug|x64.Build.0 = Debug|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Debug|x86.ActiveCfg = Debug|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Debug|x86.Build.0 = Debug|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Release|Any CPU.ActiveCfg = Release|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Release|Any CPU.Build.0 = Release|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Release|x64.ActiveCfg = Release|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Release|x64.Build.0 = Release|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Release|x86.ActiveCfg = Release|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Release|x86.Build.0 = Release|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Debug|x64.ActiveCfg = Debug|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Debug|x64.Build.0 = Debug|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Debug|x86.ActiveCfg = Debug|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Debug|x86.Build.0 = Debug|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Release|Any CPU.Build.0 = Release|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Release|x64.ActiveCfg = Release|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Release|x64.Build.0 = Release|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Release|x86.ActiveCfg = Release|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Release|x86.Build.0 = Release|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Debug|x64.ActiveCfg = Debug|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Debug|x64.Build.0 = Debug|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Debug|x86.ActiveCfg = Debug|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Debug|x86.Build.0 = Debug|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Release|Any CPU.Build.0 = Release|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Release|x64.ActiveCfg = Release|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Release|x64.Build.0 = Release|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Release|x86.ActiveCfg = Release|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Release|x86.Build.0 = Release|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Debug|x64.ActiveCfg = Debug|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Debug|x64.Build.0 = Debug|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Debug|x86.ActiveCfg = Debug|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Debug|x86.Build.0 = Debug|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Release|Any CPU.Build.0 = Release|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Release|x64.ActiveCfg = Release|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Release|x64.Build.0 = Release|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Release|x86.ActiveCfg = Release|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Release|x86.Build.0 = Release|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Debug|Any CPU.Build.0 = Debug|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Debug|x64.ActiveCfg = Debug|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Debug|x64.Build.0 = Debug|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Debug|x86.ActiveCfg = Debug|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Debug|x86.Build.0 = Debug|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Release|Any CPU.ActiveCfg = Release|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Release|Any CPU.Build.0 = Release|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Release|x64.ActiveCfg = Release|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Release|x64.Build.0 = Release|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Release|x86.ActiveCfg = Release|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Release|x86.Build.0 = Release|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Debug|x64.ActiveCfg = Debug|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Debug|x64.Build.0 = Debug|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Debug|x86.ActiveCfg = Debug|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Debug|x86.Build.0 = Debug|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Release|Any CPU.Build.0 = Release|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Release|x64.ActiveCfg = Release|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Release|x64.Build.0 = Release|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Release|x86.ActiveCfg = Release|Any CPU + {A276F6D0-18D6-4A2B-A8FE-C03CA0694DEE}.Release|x86.Build.0 = Release|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Debug|x64.ActiveCfg = Debug|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Debug|x64.Build.0 = Debug|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Debug|x86.ActiveCfg = Debug|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Debug|x86.Build.0 = Debug|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Release|Any CPU.Build.0 = Release|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Release|x64.ActiveCfg = Release|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Release|x64.Build.0 = Release|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Release|x86.ActiveCfg = Release|Any CPU + {5B3E2130-4B0A-414D-B075-7AF50B7D9B55}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CompanyEmployee.Api/CompanyEmployee.Api.csproj b/CompanyEmployee.Api/CompanyEmployee.Api.csproj new file mode 100644 index 00000000..38400e3f --- /dev/null +++ b/CompanyEmployee.Api/CompanyEmployee.Api.csproj @@ -0,0 +1,26 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + + + + + diff --git a/CompanyEmployee.Api/Controllers/EmployeeController.cs b/CompanyEmployee.Api/Controllers/EmployeeController.cs new file mode 100644 index 00000000..baa925d2 --- /dev/null +++ b/CompanyEmployee.Api/Controllers/EmployeeController.cs @@ -0,0 +1,55 @@ +using CompanyEmployee.Api.Services; +using CompanyEmployee.Domain.Entity; +using Microsoft.AspNetCore.Mvc; + +namespace CompanyEmployee.Api.Controllers; + +/// +/// Контроллер для работы с сотрудниками. +/// +/// Сервис для получения сотрудников с кэшированием. +/// Логгер для записи информации о запросах. +[ApiController] +[Route("api/[controller]")] +public class EmployeeController( + IEmployeeService employeeService, + ILogger logger) : ControllerBase +{ + /// + /// Получить сотрудника по идентификатору. + /// + /// Идентификатор сотрудника. + /// Токен отмены операции. + /// Объект сотрудника. + [HttpGet] + [ProducesResponseType(typeof(Employee), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> GetEmployee([FromQuery] int id, CancellationToken cancellationToken) + { + try + { + logger.LogInformation("Запрос на получение сотрудника с id: {Id}", id); + + if (id <= 0) + { + return BadRequest("ID должен быть положительным числом"); + } + + var employee = await employeeService.GetEmployeeAsync(id, cancellationToken); + + if (employee == null) + { + return NotFound($"Сотрудник с ID {id} не найден"); + } + + return Ok(employee); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при получении сотрудника с id: {Id}", id); + return StatusCode(500, "Внутренняя ошибка сервера"); + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.Api/Program.cs b/CompanyEmployee.Api/Program.cs new file mode 100644 index 00000000..36e3eec0 --- /dev/null +++ b/CompanyEmployee.Api/Program.cs @@ -0,0 +1,43 @@ +using Amazon.SimpleNotificationService; +using CompanyEmployee.Api.Services; +using CompanyEmployee.ServiceDefaults; +using LocalStack.Client.Extensions; +using Amazon.Extensions.NETCore.Setup; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddLocalStack(builder.Configuration); + +builder.Services.AddAwsService(); + +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapDefaultEndpoints(); + +if (!app.Environment.IsEnvironment("Testing")) +{ + app.UseHttpsRedirection(); +} + +app.UseAuthorization(); +app.MapControllers(); + +app.Run(); \ No newline at end of file diff --git a/CompanyEmployee.Api/Properties/launchSettings.json b/CompanyEmployee.Api/Properties/launchSettings.json new file mode 100644 index 00000000..c61e4ea0 --- /dev/null +++ b/CompanyEmployee.Api/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:56739", + "sslPort": 44378 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:5001", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:6001", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.Api/Services/EmployeeGenerator.cs b/CompanyEmployee.Api/Services/EmployeeGenerator.cs new file mode 100644 index 00000000..100cc7e2 --- /dev/null +++ b/CompanyEmployee.Api/Services/EmployeeGenerator.cs @@ -0,0 +1,78 @@ +using Bogus; +using Bogus.DataSets; +using CompanyEmployee.Domain.Entity; + +namespace CompanyEmployee.Api.Services; + +/// +/// Генератор сотрудников. +/// +/// Логгер. +public class EmployeeGenerator(ILogger logger) : IEmployeeGenerator +{ + private readonly string[] _professions = { "Developer", "Manager", "Analyst", "Designer", "QA" }; + private readonly string[] _suffixes = { "Junior", "Middle", "Senior" }; + + /// + public Employee Generate(int id) + { + Randomizer.Seed = new Random(id); + var faker = new Faker("ru"); + var employee = new Faker("ru") + .RuleFor(e => e.Id, id) + .RuleFor(e => e.FullName, f => + { + var gender = f.PickRandom(); + var firstName = f.Name.FirstName(gender); + var lastName = f.Name.LastName(gender); + var fatherName = f.Name.FirstName(Name.Gender.Male); + var patronymic = gender == Name.Gender.Male + ? fatherName.EndsWith("й") || fatherName.EndsWith("ь") + ? fatherName[..^1] + "евич" + : fatherName + "ович" + : fatherName.EndsWith("й") || fatherName.EndsWith("ь") + ? fatherName[..^1] + "евна" + : fatherName + "овна"; + + return $"{lastName} {firstName} {patronymic}"; + }) + .RuleFor(e => e.Position, f => + { + var profession = f.PickRandom(_professions); + var suffix = f.PickRandom(_suffixes); + return $"{profession} {suffix}"; + }) + .RuleFor(e => e.Department, f => f.Commerce.Department()) + .RuleFor(e => e.HireDate, f => + DateOnly.FromDateTime(f.Date.Past(10).ToUniversalTime())) + .RuleFor(e => e.Salary, f => + { + var suffix = f.PickRandom(_suffixes); + var salary = suffix switch + { + "Junior" => f.Random.Decimal(30000, 60000), + "Middle" => f.Random.Decimal(60000, 100000), + "Senior" => f.Random.Decimal(100000, 180000), + _ => f.Random.Decimal(40000, 80000) + }; + return Math.Round(salary, 2); + }) + .RuleFor(e => e.Email, (f, e) => + { + var nameParts = e.FullName.Split(' '); + return f.Internet.Email(nameParts[1], nameParts[0], "company.ru"); + }) + .RuleFor(e => e.Phone, f => f.Phone.PhoneNumber("+7(###)###-##-##")) + .RuleFor(e => e.IsTerminated, f => f.Random.Bool(0.1f)) + .RuleFor(e => e.TerminationDate, (f, e) => + e.IsTerminated + ? DateOnly.FromDateTime(f.Date.Between( + e.HireDate.ToDateTime(TimeOnly.MinValue), + DateTime.Now)) + : null) + .Generate(); + + logger.LogInformation("Сгенерирован сотрудник ID {Id}: {FullName}", employee.Id, employee.FullName); + return employee; + } +} \ No newline at end of file diff --git a/CompanyEmployee.Api/Services/EmployeeService.cs b/CompanyEmployee.Api/Services/EmployeeService.cs new file mode 100644 index 00000000..62bbb5cb --- /dev/null +++ b/CompanyEmployee.Api/Services/EmployeeService.cs @@ -0,0 +1,110 @@ +using System.Text.Json; +using CompanyEmployee.Domain.Entity; +using Microsoft.Extensions.Caching.Distributed; + +namespace CompanyEmployee.Api.Services; + +/// +/// Сервис для работы с сотрудниками, включая кэширование и публикацию в SNS. +/// +/// Генератор сотрудников. +/// Кэш Redis. +/// Публикатор SNS. +/// Логгер. +public class EmployeeService( + IEmployeeGenerator generator, + IDistributedCache cache, + SnsPublisherService snsPublisher, + ILogger logger) : IEmployeeService +{ + private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + + private readonly DistributedCacheEntryOptions _cacheOptions = new() + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) + }; + + /// + public async Task GetEmployeeAsync(int id, CancellationToken cancellationToken = default) + { + var cacheKey = $"employee:{id}"; + + var cachedEmployee = await TryGetFromCacheAsync(cacheKey, id, cancellationToken); + if (cachedEmployee is not null) + { + return cachedEmployee; + } + + var employee = GenerateEmployee(id); + if (employee is null) + { + return null; + } + + await SaveToCacheAsync(cacheKey, employee, id, cancellationToken); + await PublishToSnsAsync(employee, id, cancellationToken); + + return employee; + } + + private async Task TryGetFromCacheAsync(string cacheKey, int id, CancellationToken cancellationToken) + { + try + { + var cachedJson = await cache.GetStringAsync(cacheKey, cancellationToken); + if (!string.IsNullOrEmpty(cachedJson)) + { + logger.LogDebug("Employee {EmployeeId} found in cache", id); + return JsonSerializer.Deserialize(cachedJson, _jsonOptions); + } + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to retrieve employee {EmployeeId} from cache", id); + } + + return null; + } + + private Employee? GenerateEmployee(int id) + { + try + { + logger.LogDebug("Employee {EmployeeId} not found in cache, generating new employee", id); + var employee = generator.Generate(id); + logger.LogInformation("Generated employee {EmployeeId}: {FullName}", id, employee.FullName); + return employee; + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to generate employee {EmployeeId}", id); + return null; + } + } + + private async Task SaveToCacheAsync(string cacheKey, Employee employee, int id, CancellationToken cancellationToken) + { + try + { + var serialized = JsonSerializer.Serialize(employee, _jsonOptions); + await cache.SetStringAsync(cacheKey, serialized, _cacheOptions, cancellationToken); + logger.LogDebug("Employee {EmployeeId} saved to cache", id); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to save employee {EmployeeId} to cache", id); + } + } + + private async Task PublishToSnsAsync(Employee employee, int id, CancellationToken cancellationToken) + { + try + { + await snsPublisher.PublishEmployeeAsync(employee, cancellationToken); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to publish employee {EmployeeId} to SNS", id); + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.Api/Services/ICacheService.cs b/CompanyEmployee.Api/Services/ICacheService.cs new file mode 100644 index 00000000..523bf771 --- /dev/null +++ b/CompanyEmployee.Api/Services/ICacheService.cs @@ -0,0 +1,22 @@ +using Microsoft.Extensions.Caching.Distributed; + +namespace CompanyEmployee.Api.Services; + +/// +/// Сервис для работы с распределённым кэшем. +/// +public interface ICacheService +{ + /// Получает данные из кэша по ключу. + /// Ключ кэша. + /// Токен отмены. + /// Данные из кэша или default. + public Task GetAsync(string key, CancellationToken cancellationToken = default); + + /// Сохраняет данные в кэш. + /// Ключ кэша. + /// Данные для сохранения. + /// Опции кэширования. + /// Токен отмены. + public Task SetAsync(string key, T value, DistributedCacheEntryOptions? options = null, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/CompanyEmployee.Api/Services/IEmployeeGenerator.cs b/CompanyEmployee.Api/Services/IEmployeeGenerator.cs new file mode 100644 index 00000000..812b2340 --- /dev/null +++ b/CompanyEmployee.Api/Services/IEmployeeGenerator.cs @@ -0,0 +1,16 @@ +using CompanyEmployee.Domain.Entity; + +namespace CompanyEmployee.Api.Services; + +/// +/// Генератор данных сотрудников. +/// +public interface IEmployeeGenerator +{ + /// + /// Генерирует сотрудника по идентификатору. + /// + /// Идентификатор. + /// Сгенерированный сотрудник. + public Employee Generate(int id); +} \ No newline at end of file diff --git a/CompanyEmployee.Api/Services/IEmployeeService.cs b/CompanyEmployee.Api/Services/IEmployeeService.cs new file mode 100644 index 00000000..000463b8 --- /dev/null +++ b/CompanyEmployee.Api/Services/IEmployeeService.cs @@ -0,0 +1,17 @@ +using CompanyEmployee.Domain.Entity; + +namespace CompanyEmployee.Api.Services; + +/// +/// Сервис для работы с сотрудниками. +/// +public interface IEmployeeService +{ + /// + /// Получает сотрудника по идентификатору с использованием кэширования. + /// + /// Идентификатор сотрудника. + /// Токен отмены. + /// Сотрудник или null. + public Task GetEmployeeAsync(int id, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/CompanyEmployee.Api/Services/RedisCacheService.cs b/CompanyEmployee.Api/Services/RedisCacheService.cs new file mode 100644 index 00000000..e9c68aab --- /dev/null +++ b/CompanyEmployee.Api/Services/RedisCacheService.cs @@ -0,0 +1,59 @@ +using System.Text.Json; +using Microsoft.Extensions.Caching.Distributed; + +namespace CompanyEmployee.Api.Services; + +/// +/// Реализация кэширования в Redis. +/// +/// Redis Distributed Cache. +/// Логгер. +public class RedisCacheService( + IDistributedCache cache, + ILogger logger) : ICacheService +{ + /// + public async Task GetAsync(string key, CancellationToken cancellationToken = default) + { + try + { + logger.LogDebug("Получение из кэша по ключу {Key}", key); + var cachedJson = await cache.GetStringAsync(key, cancellationToken); + + if (cachedJson == null) + { + logger.LogDebug("Данные по ключу {Key} не найдены", key); + return default; + } + + return JsonSerializer.Deserialize(cachedJson); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при получении данных из кэша по ключу {Key}", key); + return default; + } + } + + /// + public async Task SetAsync(string key, T value, DistributedCacheEntryOptions? options = null, CancellationToken cancellationToken = default) + { + try + { + logger.LogDebug("Сохранение в кэш по ключу {Key}", key); + var serialized = JsonSerializer.Serialize(value); + + await cache.SetStringAsync( + key, + serialized, + options ?? new DistributedCacheEntryOptions(), + cancellationToken); + + logger.LogDebug("Данные сохранены в кэш по ключу {Key}", key); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Не удалось сохранить данные в кэш по ключу {Key}", key); + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.Api/Services/SnsPublisherService.cs b/CompanyEmployee.Api/Services/SnsPublisherService.cs new file mode 100644 index 00000000..8838eef9 --- /dev/null +++ b/CompanyEmployee.Api/Services/SnsPublisherService.cs @@ -0,0 +1,84 @@ +using System.Text.Json; +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; +using CompanyEmployee.Domain.Entity; + +namespace CompanyEmployee.Api.Services; + +/// +/// Сервис для публикации сообщений о сотрудниках в SNS. +/// +public class SnsPublisherService( + IAmazonSimpleNotificationService snsClient, + IConfiguration configuration, + ILogger logger) +{ + private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + + private readonly string _topicArn = configuration["SNS:TopicArn"] + ?? throw new InvalidOperationException("SNS:TopicArn is not configured. Please check your appsettings.json or environment variables."); + + /// + /// Публикует данные сотрудника в SNS топик. + /// + public async Task PublishEmployeeAsync(Employee employee, CancellationToken cancellationToken = default) + { + try + { + logger.LogDebug("Publishing employee {EmployeeId} to SNS topic {TopicArn}", employee.Id, _topicArn); + + var message = JsonSerializer.Serialize(employee, _jsonOptions); + var publishRequest = new PublishRequest + { + TopicArn = _topicArn, + Message = message, + Subject = $"Employee-{employee.Id}" + }; + + var response = await snsClient.PublishAsync(publishRequest, cancellationToken); + logger.LogInformation("Employee {EmployeeId} published to SNS, MessageId: {MessageId}", + employee.Id, response.MessageId); + } + catch (NotFoundException) + { + logger.LogWarning("SNS topic not found, attempting to create topic"); + await TryCreateTopicAndPublishAsync(employee, cancellationToken); + } + catch (TaskCanceledException ex) + { + logger.LogError(ex, "SNS request timed out for employee {EmployeeId}", employee.Id); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to publish employee {EmployeeId} to SNS", employee.Id); + } + } + + private async Task TryCreateTopicAndPublishAsync(Employee employee, CancellationToken cancellationToken) + { + try + { + var createTopicRequest = new CreateTopicRequest { Name = "employee-events" }; + var createResponse = await snsClient.CreateTopicAsync(createTopicRequest, cancellationToken); + var createdTopicArn = createResponse.TopicArn; + + logger.LogInformation("SNS topic created: {TopicArn}", createdTopicArn); + + var message = JsonSerializer.Serialize(employee, _jsonOptions); + var publishRequest = new PublishRequest + { + TopicArn = createdTopicArn, + Message = message, + Subject = $"Employee-{employee.Id}" + }; + + var response = await snsClient.PublishAsync(publishRequest, cancellationToken); + logger.LogInformation("Employee {EmployeeId} published after topic creation, MessageId: {MessageId}", + employee.Id, response.MessageId); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to create SNS topic and publish employee {EmployeeId}", employee.Id); + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.Api/appsettings.Development.json b/CompanyEmployee.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CompanyEmployee.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CompanyEmployee.Api/appsettings.json b/CompanyEmployee.Api/appsettings.json new file mode 100644 index 00000000..8000362d --- /dev/null +++ b/CompanyEmployee.Api/appsettings.json @@ -0,0 +1,27 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AWS": { + "ServiceURL": "http://localhost:4566", + "Region": "us-east-1", + "AccessKeyId": "test", + "SecretAccessKey": "test" + }, + "LocalStack": { + "UseLocalStack": true, + "Config": { + "LocalStackHost": "localhost", + "EdgePort": 4566 + } + }, + "SNS": { + "TopicArn": "arn:aws:sns:us-east-1:000000000000:employee-events" + }, + "FileService": { + "Url": "https://localhost:7277" + } +} \ No newline at end of file diff --git a/CompanyEmployee.AppHost/AppHost.cs b/CompanyEmployee.AppHost/AppHost.cs new file mode 100644 index 00000000..c6e8a331 --- /dev/null +++ b/CompanyEmployee.AppHost/AppHost.cs @@ -0,0 +1,63 @@ +using Amazon; +using Aspire.Hosting.LocalStack; +using Aspire.Hosting.LocalStack.Container; +using LocalStack.Client.Enums; + +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisCommander(); + +var minio = builder.AddMinioContainer("minio") + .WithDataVolume("minio-data"); + +var awsConfig = builder.AddAWSSDKConfig() + .WithRegion(RegionEndpoint.USEast1); + +var localstack = builder.AddLocalStack("localstack", awsConfig: awsConfig, configureContainer: container => +{ + container.Lifetime = ContainerLifetime.Persistent; + container.EagerLoadedServices = [AwsService.Sns]; + container.LogLevel = LocalStackLogLevel.Warn; + container.Port = 4566; +}); +builder.UseLocalStack(localstack); + +var fileService = builder.AddProject("fileservice") + .WithReference(minio) + .WithReference(localstack) + .WithEnvironment("MinIO__BucketName", "employee-data") + .WaitFor(minio); + +var gateway = builder.AddProject("gateway") + .WithExternalHttpEndpoints(); + +const int startApiHttpsPort = 6001; +var apiReplicas = new List>(); + +for (var i = 0; i < 5; i++) +{ + var httpsPort = startApiHttpsPort + i; + + var api = builder.AddProject($"api-{i + 1}") + .WithReference(redis) + .WithReference(localstack) + .WithReference(awsConfig) + .WithEndpoint("https", e => e.Port = httpsPort) + .WithEnvironment("ASPNETCORE_ENVIRONMENT", "Development") + .WaitFor(redis); + + apiReplicas.Add(api); + gateway.WaitFor(api); +} + +foreach (var replica in apiReplicas) +{ + gateway.WithReference(replica); +} + +var client = builder.AddProject("client") + .WithReference(gateway) + .WaitFor(gateway); + +builder.Build().Run(); \ No newline at end of file diff --git a/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj new file mode 100644 index 00000000..686caf18 --- /dev/null +++ b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj @@ -0,0 +1,27 @@ + + + + + + Exe + net8.0 + enable + enable + 78f7593b-e0aa-4c9f-9165-d722e0a4dde4 + + + + + + + + + + + + + + + + + diff --git a/CompanyEmployee.AppHost/Properties/launchSettings.json b/CompanyEmployee.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..6c680ac5 --- /dev/null +++ b/CompanyEmployee.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:17057;http://localhost:15121", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21201", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22004" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15121", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19103", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20107" + } + } + } +} diff --git a/CompanyEmployee.AppHost/appsettings.Development.json b/CompanyEmployee.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CompanyEmployee.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CompanyEmployee.AppHost/appsettings.json b/CompanyEmployee.AppHost/appsettings.json new file mode 100644 index 00000000..44b05554 --- /dev/null +++ b/CompanyEmployee.AppHost/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "LocalStack": { + "UseLocalStack": true + } +} \ No newline at end of file diff --git a/CompanyEmployee.AppHost/setup-sns.ps1 b/CompanyEmployee.AppHost/setup-sns.ps1 new file mode 100644 index 00000000..1f17e5d5 --- /dev/null +++ b/CompanyEmployee.AppHost/setup-sns.ps1 @@ -0,0 +1,32 @@ +Write-Host "Initializing LocalStack for SNS" + +$maxAttempts = 30 +$attempt = 0 +while ($attempt -lt $maxAttempts) { + try { + awslocal sns list-topics 2>$null + if ($LASTEXITCODE -eq 0) { + Write-Host "LocalStack is ready!" + break + } + } catch {} + $attempt++ + Write-Host "Waiting for LocalStack (attempt $attempt/$maxAttempts)" + Start-Sleep -Seconds 1 +} + +if ($attempt -eq $maxAttempts) { + Write-Host "ERROR: LocalStack failed to start" + exit 1 +} + +Write-Host "Creating SNS topic..." +awslocal sns create-topic --name employee-events + +Write-Host "Subscribing FileService to SNS topic..." +awslocal sns subscribe ` + --topic-arn arn:aws:sns:us-east-1:000000000000:employee-events ` + --protocol http ` + --notification-endpoint http://host.docker.internal:5194/api/sns/notification + +Write-Host "SNS topic created and FileService subscribed successfully" \ No newline at end of file diff --git a/CompanyEmployee.Domain/CompanyEmployee.Domain.csproj b/CompanyEmployee.Domain/CompanyEmployee.Domain.csproj new file mode 100644 index 00000000..fa71b7ae --- /dev/null +++ b/CompanyEmployee.Domain/CompanyEmployee.Domain.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/CompanyEmployee.Domain/Entity/Employee.cs b/CompanyEmployee.Domain/Entity/Employee.cs new file mode 100644 index 00000000..88b7935e --- /dev/null +++ b/CompanyEmployee.Domain/Entity/Employee.cs @@ -0,0 +1,57 @@ +namespace CompanyEmployee.Domain.Entity; + +/// +/// Представляет сотрудника компании со всеми характеристиками. +/// +public class Employee +{ + /// + /// Идентификатор сотрудника в системе + /// + public int Id { get; set; } + + /// + /// ФИО + /// + public string FullName { get; set; } = string.Empty; + + /// + /// Должность + /// + public string Position { get; set; } = string.Empty; + + /// + /// Отдел + /// + public string Department { get; set; } = string.Empty; + + /// + /// Дата приема + /// + public DateOnly HireDate { get; set; } + + /// + /// Зарплата + /// + public decimal Salary { get; set; } + + /// + /// Электронная почта + /// + public string Email { get; set; } = string.Empty; + + /// + /// Телефон + /// + public string Phone { get; set; } = string.Empty; + + /// + /// Индикатор увольнения + /// + public bool IsTerminated { get; set; } + + /// + /// Дата увольнения + /// + public DateOnly? TerminationDate { get; set; } +} \ No newline at end of file diff --git a/CompanyEmployee.FileService/CompanyEmployee.FileService.csproj b/CompanyEmployee.FileService/CompanyEmployee.FileService.csproj new file mode 100644 index 00000000..db56121f --- /dev/null +++ b/CompanyEmployee.FileService/CompanyEmployee.FileService.csproj @@ -0,0 +1,21 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + diff --git a/CompanyEmployee.FileService/Controllers/FilesController.cs b/CompanyEmployee.FileService/Controllers/FilesController.cs new file mode 100644 index 00000000..0d4bbaea --- /dev/null +++ b/CompanyEmployee.FileService/Controllers/FilesController.cs @@ -0,0 +1,90 @@ +using System.Text; +using CompanyEmployee.FileService.Services; +using Microsoft.AspNetCore.Mvc; + +namespace CompanyEmployee.FileService.Controllers; + +/// +/// Контроллер для работы с файлами сотрудников в MinIO хранилище. +/// +[ApiController] +[Route("api/files")] +public class FilesController( + IStorageService storage, + string bucketName, + ILogger logger) : ControllerBase +{ + /// + /// Получает список всех файлов в бакете. + /// + [HttpGet] + public async Task GetFiles() + { + logger.LogDebug("Retrieving file list from bucket {BucketName}", bucketName); + + var files = await storage.ListFilesAsync(bucketName); + + logger.LogInformation("Retrieved {Count} files from bucket {BucketName}", files.Count(), bucketName); + return Ok(new { count = files.Count(), files }); + } + + /// + /// Проверяет существование файла в бакете. + /// + [HttpGet("exists/{fileName}")] + public async Task FileExists(string fileName) + { + logger.LogDebug("Checking existence of file {FileName}", fileName); + + var exists = await storage.FileExistsAsync(bucketName, fileName); + + if (exists) + { + logger.LogDebug("File {FileName} exists", fileName); + return Ok(); + } + + logger.LogDebug("File {FileName} not found", fileName); + return NotFound(); + } + + /// + /// Получает метаданные файла (размер, дата изменения). + /// + [HttpGet("{fileName}/metadata")] + public async Task GetFileMetadata(string fileName) + { + logger.LogDebug("Retrieving metadata for file {FileName}", fileName); + + var metadata = await storage.GetFileMetadataAsync(bucketName, fileName); + if (metadata is null) + { + logger.LogDebug("Metadata not found for file {FileName}", fileName); + return NotFound(); + } + + logger.LogInformation("Retrieved metadata for {FileName}: {Size} bytes, modified {LastModified}", + fileName, metadata.Size, metadata.LastModified); + return Ok(metadata); + } + + /// + /// Получает содержимое файла сотрудника. + /// + [HttpGet("{fileName}")] + public async Task GetFile(string fileName) + { + logger.LogDebug("Retrieving file {FileName}", fileName); + + var content = await storage.GetFileAsync(bucketName, fileName); + if (content is null) + { + logger.LogDebug("File {FileName} not found", fileName); + return NotFound(); + } + + var json = Encoding.UTF8.GetString(content); + logger.LogInformation("File {FileName} retrieved successfully, size {Size} bytes", fileName, content.Length); + return Content(json, "application/json"); + } +} \ No newline at end of file diff --git a/CompanyEmployee.FileService/Controllers/SnsController.cs b/CompanyEmployee.FileService/Controllers/SnsController.cs new file mode 100644 index 00000000..1e7db6ad --- /dev/null +++ b/CompanyEmployee.FileService/Controllers/SnsController.cs @@ -0,0 +1,175 @@ +using System.Text.Json; +using CompanyEmployee.Domain.Entity; +using CompanyEmployee.FileService.Services; +using Microsoft.AspNetCore.Mvc; + +namespace CompanyEmployee.FileService.Controllers; + +/// +/// Контроллер для обработки SNS уведомлений от LocalStack. +/// +[ApiController] +[Route("api/sns")] +public class SnsController( + IStorageService storage, + string bucketName, + IHttpClientFactory httpClientFactory, + ILogger logger, + IConfiguration configuration) : ControllerBase +{ + private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + + /// + /// Принимает SNS уведомления от LocalStack и обрабатывает их в зависимости от типа. + /// + [HttpPost("notification")] + public async Task ReceiveNotification() + { + try + { + logger.LogInformation("SNS notification received"); + + using var reader = new StreamReader(Request.Body); + var body = await reader.ReadToEndAsync(); + logger.LogDebug("SNS body: {Body}", body); + + if (!TryParseJson(body, out var doc)) + { + return BadRequest("Invalid JSON payload"); + } + + using (doc) + { + if (!doc.RootElement.TryGetProperty("Type", out var typeElement)) + { + logger.LogWarning("Missing Type property in SNS payload"); + return BadRequest("Missing Type property"); + } + + var type = typeElement.GetString(); + logger.LogInformation("SNS notification type: {Type}", type); + + return type?.ToLowerInvariant() switch + { + "subscriptionconfirmation" => await HandleSubscriptionConfirmationAsync(doc), + "notification" => await HandleNotificationAsync(doc), + _ => HandleUnknownType(type) + }; + } + } + catch (Exception ex) + { + logger.LogError(ex, "Fatal error processing SNS notification"); + return StatusCode(500, new { error = ex.Message }); + } + } + + private bool TryParseJson(string body, out JsonDocument? document) + { + try + { + document = JsonDocument.Parse(body); + return true; + } + catch (JsonException ex) + { + logger.LogWarning(ex, "Failed to parse SNS payload as JSON"); + document = null; + return false; + } + } + + private async Task HandleSubscriptionConfirmationAsync(JsonDocument doc) + { + if (!doc.RootElement.TryGetProperty("SubscribeURL", out var urlElement)) + { + logger.LogWarning("Missing SubscribeURL in subscription confirmation"); + return BadRequest("Missing SubscribeURL"); + } + + var subscribeUrl = urlElement.GetString(); + if (string.IsNullOrWhiteSpace(subscribeUrl)) + { + logger.LogWarning("Empty SubscribeURL in subscription confirmation"); + return BadRequest("Empty SubscribeURL"); + } + + logger.LogDebug("Original SubscribeURL: {Url}", subscribeUrl); + + var fixedUrl = FixLocalStackUrl(subscribeUrl); + logger.LogInformation("Confirming subscription at: {Url}", fixedUrl); + + using var client = httpClientFactory.CreateClient(); + client.Timeout = TimeSpan.FromSeconds(30); + + try + { + using var response = await client.GetAsync(fixedUrl); + + if (response.IsSuccessStatusCode) + { + logger.LogInformation("SNS subscription confirmed successfully"); + return Ok(new { message = "Subscription confirmed" }); + } + + var responseContent = await response.Content.ReadAsStringAsync(); + logger.LogError("Failed to confirm subscription. Status: {StatusCode}, Response: {Response}", + response.StatusCode, responseContent); + return StatusCode(500, new { error = "Subscription confirmation failed" }); + } + catch (Exception ex) + { + logger.LogError(ex, "Exception during subscription confirmation request to {Url}", fixedUrl); + return StatusCode(500, new { error = ex.Message }); + } + } + + private async Task HandleNotificationAsync(JsonDocument doc) + { + if (!doc.RootElement.TryGetProperty("Message", out var messageElement)) + { + logger.LogWarning("Missing Message property in SNS notification"); + return BadRequest("Missing Message property"); + } + + var messageJson = messageElement.GetString(); + if (string.IsNullOrWhiteSpace(messageJson)) + { + logger.LogWarning("Empty Message in SNS notification"); + return Ok(); + } + + logger.LogDebug("SNS message content: {Message}", messageJson); + + var employee = JsonSerializer.Deserialize(messageJson, _jsonOptions); + if (employee is null) + { + logger.LogWarning("Failed to deserialize employee from SNS message"); + return Ok(); + } + + var fileName = $"employee_{employee.Id}.json"; + var content = JsonSerializer.SerializeToUtf8Bytes(employee); + + await storage.SaveFileAsync(bucketName, fileName, content); + logger.LogInformation("Employee {EmployeeId} saved to MinIO as {FileName}", employee.Id, fileName); + + return Ok(); + } + + private IActionResult HandleUnknownType(string? type) + { + logger.LogInformation("Unknown SNS notification type: {Type}", type); + return Ok(); + } + + private string FixLocalStackUrl(string originalUrl) + { + var localStackPort = configuration["LocalStack:Port"] ?? "4566"; + logger.LogDebug("Using LocalStack port: {Port}", localStackPort); + + return originalUrl + .Replace("localhost.localstack.cloud", "localhost") + .Replace(":4566", $":{localStackPort}"); + } +} \ No newline at end of file diff --git a/CompanyEmployee.FileService/Program.cs b/CompanyEmployee.FileService/Program.cs new file mode 100644 index 00000000..141ba65d --- /dev/null +++ b/CompanyEmployee.FileService/Program.cs @@ -0,0 +1,58 @@ +using CompanyEmployee.FileService.Services; +using CompanyEmployee.ServiceDefaults; +using Amazon.SimpleNotificationService; +using LocalStack.Client.Extensions; + +var builder = WebApplication.CreateBuilder(args); +builder.AddServiceDefaults(); + +builder.AddMinioClient("minio"); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); + +var bucketName = builder.Configuration["MinIO:BucketName"] + ?? throw new InvalidOperationException("MinIO:BucketName is not configured"); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(bucketName); +builder.Services.AddHostedService(); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +var app = builder.Build(); + +if (!app.Environment.IsEnvironment("Testing")) +{ + app.UseHttpsRedirection(); +} + +using (var scope = app.Services.CreateScope()) +{ + var storageService = scope.ServiceProvider.GetRequiredService(); + var logger = scope.ServiceProvider.GetRequiredService>(); + + try + { + await storageService.EnsureBucketExistsAsync(bucketName); + logger.LogInformation("Storage initialized successfully for bucket {BucketName}", bucketName); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to initialize storage bucket {BucketName}", bucketName); + throw; + } +} + +app.MapDefaultEndpoints(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapControllers(); + +app.Run(); \ No newline at end of file diff --git a/CompanyEmployee.FileService/Properties/launchSettings.json b/CompanyEmployee.FileService/Properties/launchSettings.json new file mode 100644 index 00000000..85d05dad --- /dev/null +++ b/CompanyEmployee.FileService/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:1928", + "sslPort": 44325 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5194", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7277;http://localhost:5194", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.FileService/Services/IStorageService.cs b/CompanyEmployee.FileService/Services/IStorageService.cs new file mode 100644 index 00000000..ec60dfb5 --- /dev/null +++ b/CompanyEmployee.FileService/Services/IStorageService.cs @@ -0,0 +1,41 @@ +namespace CompanyEmployee.FileService.Services; + +/// +/// Интерфейс для работы с объектным хранилищем. +/// +public interface IStorageService +{ + /// + /// Проверяет существование бакета и создает его, если он отсутствует. + /// + public Task EnsureBucketExistsAsync(string bucketName, CancellationToken cancellationToken = default); + /// + /// Сохраняет файл в хранилище. + /// + public Task SaveFileAsync(string bucketName, string key, byte[] content); + + /// + /// Проверяет существование файла. + /// + public Task FileExistsAsync(string bucketName, string key); + + /// + /// Возвращает список всех файлов в бакете. + /// + public Task> ListFilesAsync(string bucketName); + + /// + /// Возвращает содержимое файла. + /// + public Task GetFileAsync(string bucketName, string key); + + /// + /// Возвращает метаданные файла. + /// + public Task GetFileMetadataAsync(string bucketName, string key); +} + +/// +/// Метаданные файла. +/// +public record FileMetadata(string Name, long Size, DateTime LastModified); \ No newline at end of file diff --git a/CompanyEmployee.FileService/Services/MinioStorageService.cs b/CompanyEmployee.FileService/Services/MinioStorageService.cs new file mode 100644 index 00000000..b13dce99 --- /dev/null +++ b/CompanyEmployee.FileService/Services/MinioStorageService.cs @@ -0,0 +1,163 @@ +using Minio; +using Minio.DataModel.Args; + +namespace CompanyEmployee.FileService.Services; + +/// +/// Реализация хранилища через MinIO с использованием первичного конструктора. +/// +/// Клиент MinIO для взаимодействия с хранилищем. +/// Логгер для записи диагностических сообщений. +public class MinioStorageService( + IMinioClient minioClient, + ILogger logger) : IStorageService +{ + /// + public async Task EnsureBucketExistsAsync(string bucketName, CancellationToken cancellationToken = default) + { + try + { + var bucketExists = await minioClient.BucketExistsAsync( + new BucketExistsArgs().WithBucket(bucketName), + cancellationToken); + + if (!bucketExists) + { + await minioClient.MakeBucketAsync( + new MakeBucketArgs().WithBucket(bucketName), + cancellationToken); + logger.LogInformation("Bucket {BucketName} created successfully", bucketName); + } + else + { + logger.LogDebug("Bucket {BucketName} already exists", bucketName); + } + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to ensure bucket {BucketName} exists", bucketName); + throw; + } + } + + /// + public async Task SaveFileAsync(string bucketName, string key, byte[] content) + { + try + { + await EnsureBucketExistsAsync(bucketName); + + using var stream = new MemoryStream(content); + await minioClient.PutObjectAsync(new PutObjectArgs() + .WithBucket(bucketName) + .WithObject(key) + .WithStreamData(stream) + .WithObjectSize(stream.Length) + .WithContentType("application/json")); + + logger.LogInformation("File {Key} uploaded to MinIO successfully", key); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to upload file {Key} to bucket {BucketName}", key, bucketName); + throw; + } + } + + /// + public async Task FileExistsAsync(string bucketName, string key) + { + try + { + await minioClient.StatObjectAsync(new StatObjectArgs() + .WithBucket(bucketName) + .WithObject(key)); + return true; + } + catch (Minio.Exceptions.ObjectNotFoundException) + { + logger.LogDebug("File {Key} not found in bucket {BucketName}", key, bucketName); + return false; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Error checking file existence for {Key} in bucket {BucketName}", key, bucketName); + return false; + } + } + + /// + public async Task> ListFilesAsync(string bucketName) + { + var files = new List(); + try + { + var args = new ListObjectsArgs() + .WithBucket(bucketName) + .WithRecursive(true); + + await foreach (var item in minioClient.ListObjectsEnumAsync(args)) + { + files.Add(item.Key); + } + + logger.LogInformation("Retrieved {Count} files from bucket {BucketName}", files.Count, bucketName); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to list files from bucket {BucketName}", bucketName); + } + return files; + } + + /// + public async Task GetFileAsync(string bucketName, string key) + { + try + { + using var memoryStream = new MemoryStream(); + var args = new GetObjectArgs() + .WithBucket(bucketName) + .WithObject(key) + .WithCallbackStream(stream => stream.CopyTo(memoryStream)); + + await minioClient.GetObjectAsync(args); + logger.LogInformation("File {Key} downloaded from MinIO successfully", key); + return memoryStream.ToArray(); + } + catch (Minio.Exceptions.ObjectNotFoundException) + { + logger.LogWarning("File {Key} not found in bucket {BucketName}", key, bucketName); + return null; + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to download file {Key} from bucket {BucketName}", key, bucketName); + return null; + } + } + + /// + public async Task GetFileMetadataAsync(string bucketName, string key) + { + try + { + var args = new StatObjectArgs() + .WithBucket(bucketName) + .WithObject(key); + + var stat = await minioClient.StatObjectAsync(args); + return new FileMetadata(key, stat.Size, stat.LastModified); + } + catch (Minio.Exceptions.ObjectNotFoundException) + { + logger.LogDebug("File metadata not found for {Key} in bucket {BucketName}", key, bucketName); + return null; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to get metadata for file {Key} in bucket {BucketName}", key, bucketName); + return null; + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.FileService/Services/SnsInitializerService.cs b/CompanyEmployee.FileService/Services/SnsInitializerService.cs new file mode 100644 index 00000000..e5feed8d --- /dev/null +++ b/CompanyEmployee.FileService/Services/SnsInitializerService.cs @@ -0,0 +1,56 @@ +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; + +namespace CompanyEmployee.FileService.Services; + +/// +/// Фоновый сервис для автоматической инициализации SNS подписки при запуске FileService. +/// Создает топик employee-events и подписывает FileService на получение уведомлений. +/// +/// Клиент AWS SNS для взаимодействия с LocalStack. +/// Конфигурация приложения. +/// Логгер для диагностики. +public class SnsInitializerService( + IAmazonSimpleNotificationService snsClient, + IConfiguration configuration, + ILogger logger) : IHostedService +{ + private const string TopicName = "employee-events"; + + /// + public async Task StartAsync(CancellationToken cancellationToken) + { + try + { + logger.LogInformation("Starting SNS subscription initialization"); + + var fileServiceUrl = configuration["AWS:Resources:SNSUrl"] + ?? Environment.GetEnvironmentVariable("AWS__Resources__SNSUrl") + ?? "http://host.docker.internal:5194"; + + var subscriptionEndpoint = $"{fileServiceUrl}/api/sns/notification"; + logger.LogInformation("Subscription endpoint: {Endpoint}", subscriptionEndpoint); + + var createTopicRequest = new CreateTopicRequest { Name = TopicName }; + var createTopicResponse = await snsClient.CreateTopicAsync(createTopicRequest, cancellationToken); + logger.LogInformation("SNS topic ensured: {TopicArn}", createTopicResponse.TopicArn); + + var subscribeRequest = new SubscribeRequest + { + TopicArn = createTopicResponse.TopicArn, + Protocol = "http", + Endpoint = subscriptionEndpoint + }; + + await snsClient.SubscribeAsync(subscribeRequest, cancellationToken); + logger.LogInformation("SNS subscription created successfully"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to initialize SNS subscription"); + } + } + + /// + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} \ No newline at end of file diff --git a/CompanyEmployee.FileService/appsettings.Development.json b/CompanyEmployee.FileService/appsettings.Development.json new file mode 100644 index 00000000..c054fc38 --- /dev/null +++ b/CompanyEmployee.FileService/appsettings.Development.json @@ -0,0 +1,17 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AWS": { + "ServiceURL": "http://localhost:4566", + "Region": "us-east-1", + "AccessKeyId": "test", + "SecretAccessKey": "test" + }, + "S3": { + "BucketName": "employee-data" + } +} \ No newline at end of file diff --git a/CompanyEmployee.FileService/appsettings.json b/CompanyEmployee.FileService/appsettings.json new file mode 100644 index 00000000..1a266e49 --- /dev/null +++ b/CompanyEmployee.FileService/appsettings.json @@ -0,0 +1,24 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "ConnectionStrings": { + "minio": "Endpoint=http://localhost:9000;AccessKey=minioadmin;SecretKey=minioadmin" + }, + "AWS": { + "ServiceURL": "http://localhost:4566", + "Region": "us-east-1", + "AccessKeyId": "test", + "SecretAccessKey": "test" + }, + "LocalStack": { + "UseLocalStack": true, + "Config": { + "LocalStackHost": "localhost", + "EdgePort": 4566 + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.Gateway/CompanyEmployee.Gateway.csproj b/CompanyEmployee.Gateway/CompanyEmployee.Gateway.csproj new file mode 100644 index 00000000..31d4bc8c --- /dev/null +++ b/CompanyEmployee.Gateway/CompanyEmployee.Gateway.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + + diff --git a/CompanyEmployee.Gateway/LoadBalancers/WeightedRandomLoadBalancer.cs b/CompanyEmployee.Gateway/LoadBalancers/WeightedRandomLoadBalancer.cs new file mode 100644 index 00000000..122f831d --- /dev/null +++ b/CompanyEmployee.Gateway/LoadBalancers/WeightedRandomLoadBalancer.cs @@ -0,0 +1,82 @@ +using Ocelot.Errors; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace CompanyEmployee.Gateway.LoadBalancers; + +/// +/// Балансировщик с взвешенным случайным распределением запросов. +/// +public class WeightedRandomLoadBalancer : ILoadBalancer +{ + private readonly List _services; + private readonly Dictionary _weights; + private readonly Random _random = new(); + private readonly object _lock = new(); + + /// + /// Тип балансировщика. + /// + public string Type => nameof(WeightedRandomLoadBalancer); + + /// + /// Инициализирует новый экземпляр балансировщика с весами. + /// + /// Список сервисов. + /// Словарь весов для каждого сервиса. + public WeightedRandomLoadBalancer(List services, Dictionary weights) + { + _services = services; + _weights = weights; + } + + /// + public Task> LeaseAsync(HttpContext httpContext) + { + lock (_lock) + { + var weightedList = new List(); + + foreach (var service in _services) + { + var key = $"{service.HostAndPort.DownstreamHost}:{service.HostAndPort.DownstreamPort}"; + var weight = _weights.GetValueOrDefault(key, 1); + + for (var i = 0; i < weight; i++) + { + weightedList.Add(service); + } + } + + if (weightedList.Count == 0) + { + return Task.FromResult>( + new ErrorResponse(new List + { + new UnableToFindServiceError() + })); + } + + var selected = weightedList[_random.Next(weightedList.Count)]; + return Task.FromResult>( + new OkResponse(selected.HostAndPort)); + } + } + + /// + public void Release(ServiceHostAndPort hostAndPort) + { + } +} + +/// +/// Ошибка, возникающая когда сервис не найден. +/// +public class UnableToFindServiceError : Error +{ + public UnableToFindServiceError() + : base("Нет доступных сервисов для обработки запроса", OcelotErrorCode.UnableToFindDownstreamRouteError, 404) + { + } +} \ No newline at end of file diff --git a/CompanyEmployee.Gateway/LoadBalancers/WeightedRandomLoadBalancerFactory.cs b/CompanyEmployee.Gateway/LoadBalancers/WeightedRandomLoadBalancerFactory.cs new file mode 100644 index 00000000..866f4902 --- /dev/null +++ b/CompanyEmployee.Gateway/LoadBalancers/WeightedRandomLoadBalancerFactory.cs @@ -0,0 +1,47 @@ +using Ocelot.Configuration; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace CompanyEmployee.Gateway.LoadBalancers; + +/// +/// Фабрика для создания взвешенного случайного балансировщика. +/// +public class WeightedRandomLoadBalancerFactory : ILoadBalancerFactory +{ + private readonly Dictionary _defaultWeights = new() + { + { "localhost:6001", 5 }, + { "localhost:6002", 4 }, + { "localhost:6003", 3 }, + { "localhost:6004", 2 }, + { "localhost:6005", 1 } + }; + + /// + public Response Get(DownstreamRoute route, ServiceProviderConfiguration config) + { + var services = new List(); + + foreach (var address in route.DownstreamAddresses) + { + var serviceHostAndPort = new ServiceHostAndPort( + address.Host, + address.Port, + route.DownstreamScheme); + + var service = new Service( + $"{address.Host}:{address.Port}", + serviceHostAndPort, + string.Empty, + string.Empty, + Enumerable.Empty()); + + services.Add(service); + } + + var loadBalancer = new WeightedRandomLoadBalancer(services, _defaultWeights); + return new OkResponse(loadBalancer); + } +} \ No newline at end of file diff --git a/CompanyEmployee.Gateway/Program.cs b/CompanyEmployee.Gateway/Program.cs new file mode 100644 index 00000000..42408388 --- /dev/null +++ b/CompanyEmployee.Gateway/Program.cs @@ -0,0 +1,37 @@ +using CompanyEmployee.Gateway.LoadBalancers; +using CompanyEmployee.ServiceDefaults; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using Ocelot.Provider.Polly; +using Ocelot.LoadBalancer.Interfaces; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Configuration.AddJsonFile("ocelot.json", false, true); + +builder.Services.AddCors(options => +{ + options.AddPolicy("wasm", policy => + { + policy.AllowAnyOrigin() + .WithMethods("GET") + .WithHeaders("Content-Type"); + }); +}); + +builder.Services.AddOcelot() + .AddPolly(); + +builder.Services.AddSingleton(); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); +app.UseCors("wasm"); +app.UseHttpsRedirection(); + +await app.UseOcelot(); + +app.Run(); \ No newline at end of file diff --git a/CompanyEmployee.Gateway/Properties/launchSettings.json b/CompanyEmployee.Gateway/Properties/launchSettings.json new file mode 100644 index 00000000..55ce2e92 --- /dev/null +++ b/CompanyEmployee.Gateway/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:28509", + "sslPort": 44389 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:7000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.Gateway/appsettings.Development.json b/CompanyEmployee.Gateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CompanyEmployee.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CompanyEmployee.Gateway/appsettings.json b/CompanyEmployee.Gateway/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/CompanyEmployee.Gateway/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/CompanyEmployee.Gateway/ocelot.json b/CompanyEmployee.Gateway/ocelot.json new file mode 100644 index 00000000..3d146b4d --- /dev/null +++ b/CompanyEmployee.Gateway/ocelot.json @@ -0,0 +1,39 @@ +{ + "Routes": [ + { + "DownstreamPathTemplate": "/api/employee", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 6001 + }, + { + "Host": "localhost", + "Port": 6002 + }, + { + "Host": "localhost", + "Port": 6003 + }, + { + "Host": "localhost", + "Port": 6004 + }, + { + "Host": "localhost", + "Port": 6005 + } + ], + "UpstreamPathTemplate": "/api/employee", + "UpstreamHttpMethod": [ "GET" ], + "LoadBalancerOptions": { + "Type": "WeightedRandom", + "Key": "employee-service" + } + } + ], + "GlobalConfiguration": { + "BaseUrl": "https://localhost:7000" + } +} \ No newline at end of file diff --git a/CompanyEmployee.IntegrationTests/AppHostFixture.cs b/CompanyEmployee.IntegrationTests/AppHostFixture.cs new file mode 100644 index 00000000..f24ae6cb --- /dev/null +++ b/CompanyEmployee.IntegrationTests/AppHostFixture.cs @@ -0,0 +1,63 @@ +using System.Diagnostics; +using Aspire.Hosting; +using Aspire.Hosting.Testing; +using Microsoft.Extensions.DependencyInjection; + +namespace CompanyEmployee.IntegrationTests; + +/// +/// Фикстура для управления жизненным циклом распределенного приложения Aspire в интеграционных тестах. +/// +public class AppHostFixture : IAsyncLifetime +{ + private static readonly TimeSpan _defaultTimeout = TimeSpan.FromSeconds(180); + public DistributedApplication? App { get; private set; } + public async Task InitializeAsync() + { + var appHost = await DistributedApplicationTestingBuilder.CreateAsync(); + + appHost.Configuration["DcpPublisher:RandomizePorts"] = "false"; + appHost.Configuration["ASPIRE_ENVIRONMENT"] = "Testing"; + + appHost.Services.ConfigureHttpClientDefaults(http => + http.AddStandardResilienceHandler(options => + { + options.TotalRequestTimeout.Timeout = TimeSpan.FromMinutes(3); + options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(15); + options.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(30); + options.Retry.MaxRetryAttempts = 10; + options.Retry.Delay = TimeSpan.FromSeconds(3); + })); + + App = await appHost.BuildAsync(); + await App.StartAsync(); + + await App.ResourceNotifications.WaitForResourceHealthyAsync("redis").WaitAsync(_defaultTimeout); + await App.ResourceNotifications.WaitForResourceHealthyAsync("minio").WaitAsync(_defaultTimeout); + await App.ResourceNotifications.WaitForResourceHealthyAsync("localstack").WaitAsync(_defaultTimeout); + await App.ResourceNotifications.WaitForResourceHealthyAsync("fileservice").WaitAsync(_defaultTimeout); + await App.ResourceNotifications.WaitForResourceHealthyAsync("gateway").WaitAsync(_defaultTimeout); + + for (var i = 1; i <= 5; i++) + { + await App.ResourceNotifications.WaitForResourceHealthyAsync($"api-{i}").WaitAsync(_defaultTimeout); + } + + await Task.Delay(3000); + } + + public async Task DisposeAsync() + { + if (App != null) + { + try + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await App.DisposeAsync().AsTask().WaitAsync(cts.Token); + } + catch (OperationCanceledException) + { + } + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.IntegrationTests/BasicTest.cs b/CompanyEmployee.IntegrationTests/BasicTest.cs new file mode 100644 index 00000000..35a6d4c1 --- /dev/null +++ b/CompanyEmployee.IntegrationTests/BasicTest.cs @@ -0,0 +1,189 @@ +using Aspire.Hosting.Testing; +using CompanyEmployee.Domain.Entity; +using System.Net; +using System.Text.Json; + +namespace CompanyEmployee.IntegrationTests; + +/// +/// Базовые интеграционные тесты для проверки микросервисной архитектуры CompanyEmployee +/// +public class BasicTest : IClassFixture +{ + private readonly AppHostFixture _fixture; + private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + + public BasicTest(AppHostFixture fixture) + { + _fixture = fixture; + } + + /// + /// Проверяет, что API сервис доступен и отвечает на health check запросы. + /// + [Fact] + public async Task Api_HealthCheck_ReturnsHealthy() + { + using var httpClient = _fixture.App!.CreateHttpClient("api-1"); + using var response = await httpClient.GetAsync("/api/employee?id=1"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Проверяет, что FileService доступен и его health check эндпоинт возвращает успешный статус. + /// + [Fact] + public async Task FileService_HealthCheck_ReturnsHealthy() + { + using var httpClient = _fixture.App!.CreateHttpClient("fileservice"); + + await RetryAsync(async () => + { + using var response = await httpClient.GetAsync("/health"); + response.EnsureSuccessStatusCode(); + return response; + }, maxAttempts: 5, delayMs: 1000); + } + + /// + /// Проверяет, что API корректно генерирует и возвращает сотрудника по заданному ID. + /// + [Fact] + public async Task GetEmployee_ShouldReturnEmployee() + { + using var httpClient = _fixture.App!.CreateHttpClient("api-1"); + using var response = await httpClient.GetAsync("/api/employee?id=1"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var content = await response.Content.ReadAsStringAsync(); + var employee = JsonSerializer.Deserialize(content, _jsonOptions); + + Assert.NotNull(employee); + Assert.Equal(1, employee.Id); + Assert.False(string.IsNullOrEmpty(employee.FullName)); + } + + /// + /// Проверяет идемпотентность API: повторные запросы с одинаковым ID должны возвращать + /// + [Fact] + public async Task SameEmployeeId_ShouldReturnSameData() + { + using var httpClient = _fixture.App!.CreateHttpClient("api-1"); + + using var firstResponse = await httpClient.GetAsync("/api/employee?id=2"); + var firstContent = await firstResponse.Content.ReadAsStringAsync(); + + using var secondResponse = await httpClient.GetAsync("/api/employee?id=2"); + var secondContent = await secondResponse.Content.ReadAsStringAsync(); + + Assert.Equal(firstContent, secondContent); + } + + /// + /// Проверяет, что для разных ID генерируются разные сотрудники с уникальными данными. + /// + [Fact] + public async Task DifferentIds_ShouldGenerateDifferentEmployees() + { + using var httpClient = _fixture.App!.CreateHttpClient("api-1"); + + using var response1 = await httpClient.GetAsync("/api/employee?id=10"); + var employee1 = JsonSerializer.Deserialize( + await response1.Content.ReadAsStringAsync(), _jsonOptions); + + using var response2 = await httpClient.GetAsync("/api/employee?id=20"); + var employee2 = JsonSerializer.Deserialize( + await response2.Content.ReadAsStringAsync(), _jsonOptions); + + Assert.NotNull(employee1); + Assert.NotNull(employee2); + Assert.NotEqual(employee1.FullName, employee2.FullName); + } + + /// + /// Проверяет, что Gateway корректно распределяет запросы между репликами API сервиса. + /// + [Fact] + public async Task Gateway_ShouldDistributeRequests() + { + using var httpClient = _fixture.App!.CreateHttpClient("gateway"); + + var successCount = 0; + var requestsCount = 10; + var tasks = new List>(); + + for (var i = 0; i < requestsCount; i++) + { + var id = i + 1; + tasks.Add(Task.Run(async () => + { + try + { + using var response = await httpClient.GetAsync($"/api/employee?id={id}"); + return response.IsSuccessStatusCode; + } + catch + { + return false; + } + })); + } + + var results = await Task.WhenAll(tasks); + successCount = results.Count(r => r); + + Assert.True(successCount > 0, $"Expected at least one successful request, got {successCount}"); + } + + /// + /// Полный end-to-end тест всего пайплайна: + /// + [Fact] + public async Task FullEndToEnd_ApiToMinio_ShouldSaveFile() + { + var employeeId = Random.Shared.Next(100000, 999999); + + using var apiClient = _fixture.App!.CreateHttpClient("api-1"); + using var response = await apiClient.GetAsync($"/api/employee?id={employeeId}"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using var fileServiceClient = _fixture.App!.CreateHttpClient("fileservice"); + + for (var i = 0; i < 15; i++) + { + await Task.Delay(2000); + var fileResponse = await fileServiceClient.GetAsync($"/api/files/employee_{employeeId}.json"); + if (fileResponse.IsSuccessStatusCode) return; + } + + Assert.Fail($"File employee_{employeeId}.json not found"); + } + + /// + /// Вспомогательный метод для повторных попыток выполнения асинхронной операции. + /// + private static async Task RetryAsync( + Func> action, + int maxAttempts = 3, + int delayMs = 1000, + CancellationToken cancellationToken = default) + { + for (var attempt = 1; attempt <= maxAttempts; attempt++) + { + try + { + return await action(); + } + catch (Exception ex) when (attempt < maxAttempts && + (ex is HttpRequestException || ex is TaskCanceledException)) + { + await Task.Delay(delayMs * attempt, cancellationToken); + } + } + + return await action(); + } + +} \ No newline at end of file diff --git a/CompanyEmployee.IntegrationTests/CompanyEmployee.IntegrationTests.csproj b/CompanyEmployee.IntegrationTests/CompanyEmployee.IntegrationTests.csproj new file mode 100644 index 00000000..64ad9852 --- /dev/null +++ b/CompanyEmployee.IntegrationTests/CompanyEmployee.IntegrationTests.csproj @@ -0,0 +1,35 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + + diff --git a/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj b/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj new file mode 100644 index 00000000..6ee49167 --- /dev/null +++ b/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/CompanyEmployee.ServiceDefaults/Extensions.cs b/CompanyEmployee.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..e23f6c60 --- /dev/null +++ b/CompanyEmployee.ServiceDefaults/Extensions.cs @@ -0,0 +1,127 @@ +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; + +namespace CompanyEmployee.ServiceDefaults; + +// Adds common .NET 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/README.md b/README.md deleted file mode 100644 index dcaa5eb7..00000000 --- a/README.md +++ /dev/null @@ -1,128 +0,0 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](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). -