diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..0b487b1 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №2 "Балансировка нагрузки" + Вариант №43 "Weighted Random" + Выполнена Казаковым Андреем 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab..8e21597 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7001/api/employee" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241..edbb81d 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,6 +5,16 @@ 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 Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +25,26 @@ 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 + {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}.Release|Any CPU.ActiveCfg = Release|Any CPU + {069756DA-EFFA-4835-B69C-0849C48BE473}.Release|Any CPU.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}.Release|Any CPU.ActiveCfg = Release|Any CPU + {60C547C0-C951-4270-1D2E-4BB68A5739B6}.Release|Any CPU.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}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FD5B46C8-0F5C-493A-B5FF-708AEA44AD3D}.Release|Any CPU.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}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EEC6E8C9-9951-4CE6-DBC8-FEDF498A759B}.Release|Any CPU.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}.Release|Any CPU.ActiveCfg = Release|Any CPU + {73C5B926-EAC3-32E1-1AD5-911888B0E715}.Release|Any CPU.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 0000000..f128ff9 --- /dev/null +++ b/CompanyEmployee.Api/CompanyEmployee.Api.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + + diff --git a/CompanyEmployee.Api/Controllers/EmployeeController.cs b/CompanyEmployee.Api/Controllers/EmployeeController.cs new file mode 100644 index 0000000..365d910 --- /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(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 0000000..99a787d --- /dev/null +++ b/CompanyEmployee.Api/Program.cs @@ -0,0 +1,28 @@ +using CompanyEmployee.Api.Services; +using CompanyEmployee.ServiceDefaults; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("redis"); +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapDefaultEndpoints(); +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 0000000..d5306a4 --- /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": "http://localhost:6001", + "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 0000000..100cc7e --- /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 0000000..11b2956 --- /dev/null +++ b/CompanyEmployee.Api/Services/EmployeeService.cs @@ -0,0 +1,40 @@ +using CompanyEmployee.Domain.Entity; +using Microsoft.Extensions.Caching.Distributed; + +namespace CompanyEmployee.Api.Services; + +/// +/// Бизнес-логика работы с сотрудниками. +/// +/// Генератор сотрудников. +/// Сервис кэширования. +/// Логгер. +public class EmployeeService( + IEmployeeGenerator generator, + ICacheService cache, + ILogger logger) : IEmployeeService +{ + private readonly DistributedCacheEntryOptions _cacheOptions = new() + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) + }; + + /// + public async Task GetEmployeeAsync(int id, CancellationToken cancellationToken = default) + { + var cacheKey = $"employee:{id}"; + var employee = await cache.GetAsync(cacheKey, cancellationToken); + if (employee != null) + { + logger.LogInformation("Сотрудник с ID {Id} найден в кэше", id); + return employee; + } + + logger.LogInformation("Сотрудник с ID {Id} не найден в кэше, генерация нового", id); + employee = generator.Generate(id); + + await cache.SetAsync(cacheKey, employee, _cacheOptions, cancellationToken); + + return employee; + } +} \ 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 0000000..523bf77 --- /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 0000000..812b234 --- /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 0000000..000463b --- /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 0000000..e9c68aa --- /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/appsettings.Development.json b/CompanyEmployee.Api/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /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 0000000..10f68b8 --- /dev/null +++ b/CompanyEmployee.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/CompanyEmployee.AppHost/AppHost.cs b/CompanyEmployee.AppHost/AppHost.cs new file mode 100644 index 0000000..9622058 --- /dev/null +++ b/CompanyEmployee.AppHost/AppHost.cs @@ -0,0 +1,29 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisCommander(containerName: "redis-commander"); + +var gateway = builder.AddProject("gateway") + .WithEndpoint("https", e => e.Port = 7001) + .WithExternalHttpEndpoints(); + +const int startApiPort = 6001; +const int replicaCount = 5; + +for (var i = 0; i < replicaCount; i++) +{ + var port = startApiPort + i; + var api = builder.AddProject($"api-{i + 1}") + .WithEndpoint("https", e => e.Port = port) + .WithReference(redis) + .WithEnvironment("ASPNETCORE_ENVIRONMENT", "Development") + .WaitFor(redis); + + gateway.WaitFor(api); +} + +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 0000000..60dac8d --- /dev/null +++ b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj @@ -0,0 +1,25 @@ + + + + + + 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 0000000..6c680ac --- /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 0000000..0c208ae --- /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 0000000..31c092a --- /dev/null +++ b/CompanyEmployee.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CompanyEmployee.Domain/CompanyEmployee.Domain.csproj b/CompanyEmployee.Domain/CompanyEmployee.Domain.csproj new file mode 100644 index 0000000..fa71b7a --- /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 0000000..88b7935 --- /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.Gateway/CompanyEmployee.Gateway.csproj b/CompanyEmployee.Gateway/CompanyEmployee.Gateway.csproj new file mode 100644 index 0000000..31d4bc8 --- /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 0000000..122f831 --- /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 0000000..866f490 --- /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 0000000..4240838 --- /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 0000000..3c66d5c --- /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:7001", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7001", + "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 0000000..0c208ae --- /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 0000000..10f68b8 --- /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 0000000..1bf4faf --- /dev/null +++ b/CompanyEmployee.Gateway/ocelot.json @@ -0,0 +1,44 @@ +{ + "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" + }, + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 30000, + "TimeoutValue": 5000 + } + } + ], + "GlobalConfiguration": { + "BaseUrl": "https://localhost:7001" + } +} \ No newline at end of file diff --git a/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj b/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj new file mode 100644 index 0000000..6ee4916 --- /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 0000000..e23f6c6 --- /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 dcaa5eb..0000000 --- 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). -