diff --git a/ApiGateway/ApiGateway.csproj b/ApiGateway/ApiGateway.csproj new file mode 100644 index 00000000..ea1e7972 --- /dev/null +++ b/ApiGateway/ApiGateway.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/ApiGateway/Program.cs b/ApiGateway/Program.cs new file mode 100644 index 00000000..bf176745 --- /dev/null +++ b/ApiGateway/Program.cs @@ -0,0 +1,10 @@ +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +app.MapGet("/", () => "Hello World!"); + +app.Run(); diff --git a/ApiGateway/Properties/launchSettings.json b/ApiGateway/Properties/launchSettings.json new file mode 100644 index 00000000..28198809 --- /dev/null +++ b/ApiGateway/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:49541", + "sslPort": 44328 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5176", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7163;http://localhost:5176", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/ApiGateway/appsettings.Development.json b/ApiGateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/ApiGateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/ApiGateway/appsettings.json b/ApiGateway/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/ApiGateway/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..01ab8d17 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 "Кэширование" + Вариант №5 "Сотрудник компании" + Выполнена Дубовой Ксенией 6511 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea7..60120ec3 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -12,7 +12,7 @@ "http": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "http://localhost:5127", "environmentVariables": { @@ -22,7 +22,7 @@ "https": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "https://localhost:7282;http://localhost:5127", "environmentVariables": { @@ -31,7 +31,7 @@ }, "IIS Express": { "commandName": "IISExpress", - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..834906f4 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -1,10 +1,10 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*", - "BaseAddress": "" + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "BaseAddress": "http://localhost:5212/api/CompanyEmployee" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..1f4c0cb4 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -1,10 +1,18 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.14.36811.4 +# Visual Studio Version 18 +VisualStudioVersion = 18.3.11520.95 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.ApiService", "CompanyEmployee.ApiService\CompanyEmployee.ApiService.csproj", "{744675CA-BC69-5513-0A1B-3BCC004F02F1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.AppHost", "CompanyEmployee.AppHost\CompanyEmployee.AppHost.csproj", "{B9ED18C6-0485-F2DF-93F0-2F0EACE5381F}" +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.ApiGateway", "CompanyEmployee.ApiGateway\CompanyEmployee.ApiGateway.csproj", "{D0087FC1-B713-A582-9A28-3814270CFDAD}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +23,22 @@ 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 + {744675CA-BC69-5513-0A1B-3BCC004F02F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {744675CA-BC69-5513-0A1B-3BCC004F02F1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {744675CA-BC69-5513-0A1B-3BCC004F02F1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {744675CA-BC69-5513-0A1B-3BCC004F02F1}.Release|Any CPU.Build.0 = Release|Any CPU + {B9ED18C6-0485-F2DF-93F0-2F0EACE5381F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9ED18C6-0485-F2DF-93F0-2F0EACE5381F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9ED18C6-0485-F2DF-93F0-2F0EACE5381F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9ED18C6-0485-F2DF-93F0-2F0EACE5381F}.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 + {D0087FC1-B713-A582-9A28-3814270CFDAD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D0087FC1-B713-A582-9A28-3814270CFDAD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D0087FC1-B713-A582-9A28-3814270CFDAD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D0087FC1-B713-A582-9A28-3814270CFDAD}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CompanyEmployee.ApiGateway/CompanyEmployee.ApiGateway.csproj b/CompanyEmployee.ApiGateway/CompanyEmployee.ApiGateway.csproj new file mode 100644 index 00000000..a4bad947 --- /dev/null +++ b/CompanyEmployee.ApiGateway/CompanyEmployee.ApiGateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/CompanyEmployee.ApiGateway/LoadBalancer/WeightedRoundRobin.cs b/CompanyEmployee.ApiGateway/LoadBalancer/WeightedRoundRobin.cs new file mode 100644 index 00000000..8adff936 --- /dev/null +++ b/CompanyEmployee.ApiGateway/LoadBalancer/WeightedRoundRobin.cs @@ -0,0 +1,58 @@ +using Ocelot.LoadBalancer.Errors; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Values; + +namespace CompanyEmployee.ApiGateway.LoadBalancer; + +public class WeightedRoundRobin : ILoadBalancer +{ + private static List _expandedList = new(); + private static int _index = 0; + private static readonly object _lock = new(); + private static bool _initialized = false; + + public string Type => nameof(WeightedRoundRobin); + + public WeightedRoundRobin( + List services, + IConfiguration config) + { + if (_initialized) return; + + var weights = config + .GetSection("LoadBalancerWeights") + .Get>() ?? new(); + + + foreach (var s in services) + { + + var key = s.DownstreamPort.ToString(); + var weight = weights.TryGetValue(key, out var w) ? w : 1; + + for (var i = 0; i < weight; i++) + { + _expandedList.Add(s); + } + } + + _initialized = true; + + } + + public Task> LeaseAsync(HttpContext context) + { + lock (_lock) + { + var s = _expandedList[_index]; + _index = (_index + 1) % _expandedList.Count; + + return Task.FromResult>( + new OkResponse(s)); + } + } + + public void Release(ServiceHostAndPort hostAndPort) { } +} \ No newline at end of file diff --git a/CompanyEmployee.ApiGateway/Program.cs b/CompanyEmployee.ApiGateway/Program.cs new file mode 100644 index 00000000..d4a7866f --- /dev/null +++ b/CompanyEmployee.ApiGateway/Program.cs @@ -0,0 +1,28 @@ +using CompanyEmployee.ApiGateway.LoadBalancer; +using Ocelot.DependencyInjection; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Middleware; +using Ocelot.Values; + +var builder = WebApplication.CreateBuilder(args); + +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); + +builder.Services + .AddOcelot(builder.Configuration) + .AddCustomLoadBalancer((route, _) => + { + var config = builder.Configuration; + + var services = route.DownstreamAddresses + .Select(h => new ServiceHostAndPort(h.Host, h.Port)) + .ToList(); + + return new WeightedRoundRobin(services, config); + }); + +var app = builder.Build(); + +await app.UseOcelot(); + +app.Run(); \ No newline at end of file diff --git a/CompanyEmployee.ApiGateway/Properties/launchSettings.json b/CompanyEmployee.ApiGateway/Properties/launchSettings.json new file mode 100644 index 00000000..26a0a4a9 --- /dev/null +++ b/CompanyEmployee.ApiGateway/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:26883", + "sslPort": 44388 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5212", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7092;http://localhost:5212", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CompanyEmployee.ApiGateway/appsettings.Development.json b/CompanyEmployee.ApiGateway/appsettings.Development.json new file mode 100644 index 00000000..e3eca24a --- /dev/null +++ b/CompanyEmployee.ApiGateway/appsettings.Development.json @@ -0,0 +1,11 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "GlobalConfiguration": { + "BaseUrl": "https://localhost:5212" + } +} diff --git a/CompanyEmployee.ApiGateway/appsettings.json b/CompanyEmployee.ApiGateway/appsettings.json new file mode 100644 index 00000000..fd379c6d --- /dev/null +++ b/CompanyEmployee.ApiGateway/appsettings.json @@ -0,0 +1,14 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "LoadBalancerWeights": { + "5213": 1, + "5214": 2, + "5215": 1 + }, + "AllowedHosts": "*" +} diff --git a/CompanyEmployee.ApiGateway/ocelot.json b/CompanyEmployee.ApiGateway/ocelot.json new file mode 100644 index 00000000..085c656f --- /dev/null +++ b/CompanyEmployee.ApiGateway/ocelot.json @@ -0,0 +1,28 @@ +{ + "Generators": [ "generator-1", "generator-2", "generator-3" ], + "Routes": [ + { + "DownstreamPathTemplate": "/api/CompanyEmployee", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 5213 + }, + { + "Host": "localhost", + "Port": 5214 + }, + { + "Host": "localhost", + "Port": 5215 + } + ], + "UpstreamPathTemplate": "/api/CompanyEmployee", + "UpstreamHttpMethod": [ "GET" ], + "LoadBalancerOptions": { + "Type": "WeightedRoundRobin" + } + } + ] +} \ No newline at end of file diff --git a/CompanyEmployee.ApiService/CompanyEmployee.ApiService.csproj b/CompanyEmployee.ApiService/CompanyEmployee.ApiService.csproj new file mode 100644 index 00000000..657e2a75 --- /dev/null +++ b/CompanyEmployee.ApiService/CompanyEmployee.ApiService.csproj @@ -0,0 +1,21 @@ + + + + net8.0 + true + enable + enable + + + + + + + + + + + + + + diff --git a/CompanyEmployee.ApiService/CompanyEmployee.ApiService.http b/CompanyEmployee.ApiService/CompanyEmployee.ApiService.http new file mode 100644 index 00000000..f99dafc2 --- /dev/null +++ b/CompanyEmployee.ApiService/CompanyEmployee.ApiService.http @@ -0,0 +1,6 @@ +@ApiService_HostAddress = http://localhost:5497 + +GET {{ApiService_HostAddress}}/weatherforecast/ +Accept: application/json + +### \ No newline at end of file diff --git a/CompanyEmployee.ApiService/Models/CompanyEmployeeModel.cs b/CompanyEmployee.ApiService/Models/CompanyEmployeeModel.cs new file mode 100644 index 00000000..d8ce2d6f --- /dev/null +++ b/CompanyEmployee.ApiService/Models/CompanyEmployeeModel.cs @@ -0,0 +1,57 @@ +namespace CompanyEmployee.ApiService.Models; + +/// +/// Модель сотрудника компании +/// +public class CompanyEmployeeModel +{ + /// + /// Идентификатор сотрудника в системе + /// + public required int Id { get; set; } + + /// + /// ФИО + /// + public required string FullName { get; set; } + + /// + /// Должность + /// + public required string JobTitle { get; set; } + + /// + /// Отдел + /// + public required string Department { get; set; } + + /// + /// Дата приема + /// + public required DateOnly AdmissionDate { get; set; } + + /// + /// Оклад + /// + public required decimal Salary { get; set; } + + /// + /// Электронная почта + /// + public required string Email { get; set; } + + /// + /// Номер телефона + /// + public required string PhoneNumber { get; set; } + + /// + /// Индикатор увольнения + /// + public bool Dismissal { get; set; } = false; + + /// + /// Дата увольнения + /// + public DateOnly? DismissalDate { get; set; } +} diff --git a/CompanyEmployee.ApiService/Program.cs b/CompanyEmployee.ApiService/Program.cs new file mode 100644 index 00000000..90178ec1 --- /dev/null +++ b/CompanyEmployee.ApiService/Program.cs @@ -0,0 +1,51 @@ +using CompanyEmployee.ApiService.Services; +using CompanyEmployee.ServiceDefaults; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(options => +{ + var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + + options.IncludeXmlComments(xmlPath); +}); + +builder.Services.AddCors(options => +{ + options.AddPolicy("wasm", policy => + { + policy.WithOrigins("https://localhost:7282") + .AllowAnyMethod() + .AllowAnyHeader(); + }); +}); + +builder.Services.AddScoped(); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapDefaultEndpoints(); +app.UseHttpsRedirection(); +app.UseCors("wasm"); + +app.MapGet("/api/CompanyEmployee", async (HttpContext context, CompanyEmployeeService service, int id) => +{ + var employee = await service.GetEmployeeAsync(id); + + return Results.Ok(employee); +}) +.WithSummary("Получение сотрудника по идентификатору") +.WithDescription("Возвращает информацию о сотруднике по id"); + +app.Run(); \ No newline at end of file diff --git a/CompanyEmployee.ApiService/Properties/launchSettings.json b/CompanyEmployee.ApiService/Properties/launchSettings.json new file mode 100644 index 00000000..09b1f87b --- /dev/null +++ b/CompanyEmployee.ApiService/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CompanyEmployee.ApiService/Services/CompanyEmploeeGenerator.cs b/CompanyEmployee.ApiService/Services/CompanyEmploeeGenerator.cs new file mode 100644 index 00000000..651e9a6e --- /dev/null +++ b/CompanyEmployee.ApiService/Services/CompanyEmploeeGenerator.cs @@ -0,0 +1,119 @@ +using Bogus; +using Bogus.DataSets; +using CompanyEmployee.ApiService.Models; + +namespace CompanyEmployee.ApiService.Services; + +/// +/// Генератор сотрудника +/// +public static class CompanyEmployeeGenerator +{ + + /// + /// Справочник профессий сотрудников + /// + private static readonly string[] _professionTypes = + [ + "Developer", + "Manager", + "Analyst" + ]; + + /// + /// Справочник суффиксов для профессий + /// + private static readonly string[] _suffix = + [ + "Junior", + "Middle", + "Senior" + ]; + + /// + /// Генерация должности + /// + private static string GenerateJobTitle(Faker f) + { + var suffix = f.PickRandom(_suffix); + var profession = f.PickRandom(_professionTypes); + + return $"{suffix} {profession}"; + } + + /// + /// Генерация зарплаты + /// + private static decimal GenerateSalary(Faker f, string jobTitle) + { + var level = jobTitle.Split(' ')[0]; + + var (min, max) = level switch + { + "Junior" => (50000m, 90000m), + "Middle" => (90000m, 150000m), + "Senior" => (150000m, 250000m), + _ => (50000m, 250000m) + }; + + return Math.Round(f.Random.Decimal(min, max), 2); + } + + /// + /// Генерация полного имени + /// + private static string GenerateFullName(Faker 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); + + string patronymic; + + if (fatherName.EndsWith("й") || fatherName.EndsWith("ь")) + { + patronymic = fatherName[..^1] + (gender == Name.Gender.Male ? "евич" : "евна"); + } + else + { + patronymic = fatherName + (gender == Name.Gender.Male ? "ович" : "овна"); + } + + return $"{lastName} {firstName} {patronymic}"; + } + + /// + /// Генерация даты уволнения + /// + private static DateOnly? GenerateDismissalDate(Faker f, bool Dismissal, DateOnly AdmissionDate) + { + return Dismissal ? f.Date.BetweenDateOnly(AdmissionDate, DateOnly.FromDateTime(DateTime.UtcNow)) : null; + } + + /// + /// Преднастроенный генератор + /// + private static readonly Faker _faker = new Faker("ru") + .RuleFor(e => e.FullName, GenerateFullName) + .RuleFor(e => e.JobTitle, GenerateJobTitle) + .RuleFor(e => e.Department, f => f.Commerce.Department()) + .RuleFor(e => e.AdmissionDate, f => f.Date.PastDateOnly(10)) + .RuleFor(e => e.Salary, (f, e) => GenerateSalary(f, e.JobTitle)) + .RuleFor(e => e.Email, (f, e) => f.Internet.Email()) + .RuleFor(x => x.PhoneNumber, f => f.Phone.PhoneNumber("+7(###)###-##-##")) + .RuleFor(x => x.Dismissal, f => f.Random.Bool()) + .RuleFor(x => x.DismissalDate, (f, e) => GenerateDismissalDate(f, e.Dismissal, e.AdmissionDate)); + + /// + /// Генерация сотрудника + /// + public static CompanyEmployeeModel Generate(int id) + { + var emploee = _faker.Generate(); + emploee.Id = id; + return emploee; + } +} diff --git a/CompanyEmployee.ApiService/Services/CompanyEmployeeService.cs b/CompanyEmployee.ApiService/Services/CompanyEmployeeService.cs new file mode 100644 index 00000000..4789c18e --- /dev/null +++ b/CompanyEmployee.ApiService/Services/CompanyEmployeeService.cs @@ -0,0 +1,54 @@ +using System.Text.Json; +using CompanyEmployee.ApiService.Models; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Configuration; + +namespace CompanyEmployee.ApiService.Services; + +/// +/// Сервис для получения данных сотрудника +/// +/// кэш Redis +/// логгер +/// конфигурация +public class CompanyEmployeeService(IDistributedCache cache, ILogger logger, IConfiguration configuration) +{ + private readonly int _cacheTime = configuration.GetValue("Constants:CacheTime"); + + /// + /// Получение данных сотрудника по его id, при отсутствии генерация сотрудника + /// + /// + /// + public async Task GetEmployeeAsync(int id) + { + var cacheKey = $"employee:{id}"; + + var cachedEmployee = await cache.GetStringAsync(cacheKey); + + if (cachedEmployee != null) + { + var employeeModel = JsonSerializer.Deserialize(cachedEmployee); + + if (employeeModel != null) + { + logger.LogInformation("Сотрудник №{Id} получен из кэша", id); + return employeeModel; + } + } + + logger.LogInformation("Генерация сотрудника №{Id}", id); + + var employee = CompanyEmployeeGenerator.Generate(id); + + await cache.SetStringAsync( + cacheKey, + JsonSerializer.Serialize(employee), + new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_cacheTime) + }); + + return employee; + } +} \ No newline at end of file diff --git a/CompanyEmployee.ApiService/appsettings.Development.json b/CompanyEmployee.ApiService/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CompanyEmployee.ApiService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CompanyEmployee.ApiService/appsettings.json b/CompanyEmployee.ApiService/appsettings.json new file mode 100644 index 00000000..e13474b3 --- /dev/null +++ b/CompanyEmployee.ApiService/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "Constants": { + "CacheTime": 5 + } + //"AllowedHosts": "*" +} diff --git a/CompanyEmployee.AppHost/AppHost.cs b/CompanyEmployee.AppHost/AppHost.cs new file mode 100644 index 00000000..7706f9e4 --- /dev/null +++ b/CompanyEmployee.AppHost/AppHost.cs @@ -0,0 +1,38 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis").WithRedisInsight(); + +var generator1 = builder.AddProject("generator-1") + .WithHttpEndpoint(name: "http1", port: 5213) + .WithReference(redis) + .WaitFor(redis); + +var generator2 = builder.AddProject("generator-2") + .WithHttpEndpoint(name: "http1", port: 5214) + .WithReference(redis) + .WaitFor(redis); + +var generator3 = builder.AddProject("generator-3") + .WithHttpEndpoint(name: "http1", port: 5215) + .WithReference(redis) + .WaitFor(redis); + + + +var api = builder.AddProject("companyemployee-apigateway") + .WithReference(redis) + .WaitFor(redis) + .WithReference(generator1) + .WithReference(generator2) + .WithReference(generator3) + .WithHttpEndpoint(name: "gateway", port: 5212) + .WaitFor(generator1) + .WaitFor(generator2) + .WaitFor(generator3); + +builder.AddProject("client") + .WithReference(api) + .WaitFor(api) + .WithExternalHttpEndpoints(); + +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..17aff747 --- /dev/null +++ b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj @@ -0,0 +1,21 @@ + + + + Exe + net8.0 + enable + enable + 01ffeafe-d69d-475f-88f3-14a7f4a2b6a2 + + + + + + + + + + + + + diff --git a/CompanyEmployee.AppHost/Properties/launchSettings.json b/CompanyEmployee.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..b54c9089 --- /dev/null +++ b/CompanyEmployee.AppHost/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17006;http://localhost:15069", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21138", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23203", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22209" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15069", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19233", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18122", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20090" + } + } + } +} 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..31c092aa --- /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.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj b/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj new file mode 100644 index 00000000..8ad67261 --- /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..1acdcbbc --- /dev/null +++ b/CompanyEmployee.ServiceDefaults/Extensions.cs @@ -0,0 +1,116 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Hosting; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace CompanyEmployee.ServiceDefaults; + +/// +/// Настройка для сервисов Aspire +/// +public static class Extensions +{ + private const string HealthEndpointPath = "/health"; + private const string AlivenessEndpointPath = "/alive"; + + /// + /// Добавление стандартных настроек Aspire для сервисов + /// + public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.ConfigureOpenTelemetry(); + + builder.AddDefaultHealthChecks(); + + builder.Services.AddServiceDiscovery(); + + builder.Services.ConfigureHttpClientDefaults(http => + { + http.AddStandardResilienceHandler(); + + http.AddServiceDiscovery(); + }); + + return builder; + } + + /// + /// Настройка OpenTelemetry + /// + 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 => + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + .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(); + } + + return builder; + } + + /// + /// Добавление стандартных health checks + /// + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Services.AddHealthChecks() + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + /// + /// Настройка стандартных endpoints (health checks) + /// + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + if (app.Environment.IsDevelopment()) + { + app.MapHealthChecks(HealthEndpointPath); + + app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} \ No newline at end of file diff --git a/README.md b/README.md index dcaa5eb7..19dd7c7c 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,36 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing) +# Лабораторная работа №2: «Балансировка нагрузки» — реализация API-гейтвея и настройка его работы +# Вариант №5: Сотрудник компании +Реализация микросервиса генерации сотрудника компании с кэшированием и оркестрацией на базе .NET Aspire. -## Задание -### Цель +# Цель Реализация проекта микросервисного бекенда. -### Задачи -* Реализация межсервисной коммуникации, -* Изучение работы с брокерами сообщений, -* Изучение архитектурных паттернов, -* Изучение работы со средствами оркестрации на примере .NET Aspire, -* Повторение основ работы с системами контроля версий, -* Интеграционное тестирование. +# Задачи: -### Лабораторные работы -
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов -
- -В рамках первой лабораторной работы необходимо: -* Реализовать сервис генерации контрактов на основе Bogus, -* Реализовать кеширование при помощи IDistributedCache и Redis, -* Реализовать структурное логирование сервиса генерации, -* Настроить оркестрацию Aspire. - -
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы -
- -В рамках второй лабораторной работы необходимо: -* Настроить оркестрацию на запуск нескольких реплик сервиса генерации, -* Реализовать апи гейтвей на основе Ocelot, -* Имплементировать алгоритм балансировки нагрузки согласно варианту. +1 - Настроить оркестрацию на запуск нескольких реплик сервиса генерации, +2 - Реализовать API-гейтвей на основе Ocelot, +3 - Внедрить алгоритм балансировки нагрузки в соответствии с вариантом. -
-
-
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда -
+# Комментарии к характеристикам генерации: +1 - ФИО - конкатенация фамилии, имени и отчества через пробел, все из раздела Name -В рамках третьей лабораторной работы необходимо: -* Добавить в оркестрацию объектное хранилище, -* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище, -* Реализовать отправку генерируемых данных в файловый сервис посредством брокера, -* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе. +2 - Должность выбирается из двух заранее подготовленных справочников - справочника профессий (“Developer”, “Manager”, “Analyst” и т.д.) и суффиксов к ним (“Junior”, “Middle”, “Senior” и т.д.) -
-
-
-4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud -
- -В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы: -* Клиент - в хостинг через отдельный бакет Object Storage, -* Сервис генерации - в Cloud Function, -* Апи гейтвей - в Serverless Integration как API Gateway, -* Брокер сообщений - в Message Queue, -* Файловый сервис - в Cloud Function, -* Объектное хранилище - в отдельный бакет Object Storage, +3 - Отдел берется из раздела Commerce -
-
+4 - Дата приема берется не более, чем 10 лет назад от текущей даты -## Задание. Общая часть -**Обязательно**: -* Реализация серверной части на [.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 с информацией о задании, скриншоты приложения и прочая информация. +5 - Генерация суммы оклада должна коррелировать с суффиксом должности и не иметь более 2 знаков в дробной части -**Факультативно**: -* Перенос бекенда на облачную инфраструктуру Yandex Cloud +6 - Электронная почта генерируется из раздела Internet -Внимательно прочитайте [дискуссии](https://github.com/itsecd/cloud-development/discussions/1) о том, как работает автоматическое распределение на ревью. -Сразу корректно называйте свои pr, чтобы они попали на ревью нужному преподавателю. +7 - При отсутствии индикатора увольнения дата увольнения не заполняется -По итогу работы в семестре должна получиться следующая информационная система: -
-C4 диаграмма -Современные_технологии_разработки_ПО_drawio -
+8 - Телефонный номер должен браться из раздела Phone и быть формата +7(***)***-**-** -## Варианты заданий -Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи. +# Скриншоты +image +image -[Список вариантов](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).