diff --git a/Api.Gateway/Api.Gateway.csproj b/Api.Gateway/Api.Gateway.csproj new file mode 100644 index 00000000..7e514f88 --- /dev/null +++ b/Api.Gateway/Api.Gateway.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/Api.Gateway/Balancing/WeightedRoundRobin.cs b/Api.Gateway/Balancing/WeightedRoundRobin.cs new file mode 100644 index 00000000..e642afde --- /dev/null +++ b/Api.Gateway/Balancing/WeightedRoundRobin.cs @@ -0,0 +1,43 @@ +using Microsoft.Extensions.Configuration; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace Api.Gateway.Balancing; + +/// +/// Реализация алгоритма балансировки нагрузки "Взвешенный круговой обход" (Weighted Round Robin). +/// +/// +/// +public class WeightedRoundRobin(Func>> services, IConfiguration configuration) : ILoadBalancer +{ + private static readonly object _locker = new(); + + private readonly int[] _weights = configuration + .GetSection("WeightsRoundRobin") + .Get() ?? [1, 2, 3, 4, 5]; + private int _lastIndex = 0; + private int _currentWeight = 0; + + public string Type => nameof(WeightedRoundRobin); + + public async Task> LeaseAsync(HttpContext httpContext) + { + var servicesList = await services(); + if (servicesList.Count == 0) + throw new InvalidOperationException("No available downstream services"); + lock (_locker) + { + if(_currentWeight >= _weights[_lastIndex]) + { + _currentWeight = 0; + _lastIndex = (_lastIndex +1 >= _weights.Length) ? 0 : _lastIndex + 1; + } + _currentWeight++; + return new OkResponse(servicesList[_lastIndex].HostAndPort); + } + } + + public void Release(ServiceHostAndPort hostAndPort) { } +} \ No newline at end of file diff --git a/Api.Gateway/Program.cs b/Api.Gateway/Program.cs new file mode 100644 index 00000000..5cf66c3c --- /dev/null +++ b/Api.Gateway/Program.cs @@ -0,0 +1,40 @@ +using Api.Gateway.Balancing; +using CloudDevelopment.ServiceDefaults; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddServiceDiscovery(); +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); + +var overrides = new Dictionary(); +for (var i = 0; Environment.GetEnvironmentVariable($"services__service-api-{i}__https__0") is { } url; i++) +{ + var uri = new Uri(url); + overrides[$"Routes:0:DownstreamHostAndPorts:{i}:Host"] = uri.Host; + overrides[$"Routes:0:DownstreamHostAndPorts:{i}:Port"] = uri.Port.ToString(); +} + +if (overrides.Count > 0) + builder.Configuration.AddInMemoryCollection(overrides); + +builder.Services.AddOcelot() + .AddCustomLoadBalancer((sp, _, provider) => + new WeightedRoundRobin(provider.GetAsync, sp.GetRequiredService())); + +builder.Services.AddCors(options => options.AddDefaultPolicy(policy => +{ + policy.AllowAnyOrigin(); + policy.AllowAnyMethod(); + policy.AllowAnyHeader(); +})); + +builder.AddServiceDefaults(); +var app = builder.Build(); + +app.MapDefaultEndpoints(); +app.UseCors(); +await app.UseOcelot(); + +app.Run(); diff --git a/Api.Gateway/Properties/launchSettings.json b/Api.Gateway/Properties/launchSettings.json new file mode 100644 index 00000000..12d385df --- /dev/null +++ b/Api.Gateway/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:35010", + "sslPort": 44322 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5293", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7121;http://localhost:5293", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Api.Gateway/appsettings.Development.json b/Api.Gateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Api.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Api.Gateway/appsettings.json b/Api.Gateway/appsettings.json new file mode 100644 index 00000000..188602e0 --- /dev/null +++ b/Api.Gateway/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "WeightsRoundRobin": [ 5, 4, 3, 2, 1 ] +} diff --git a/Api.Gateway/ocelot.json b/Api.Gateway/ocelot.json new file mode 100644 index 00000000..21daf9f1 --- /dev/null +++ b/Api.Gateway/ocelot.json @@ -0,0 +1,35 @@ +{ + "Routes": [ + { + "UpstreamPathTemplate": "/study-course", + "UpstreamHttpMethod": [ "GET" ], + "DownstreamPathTemplate": "/api/study-course", + "DownstreamScheme": "https", + "LoadBalancerOptions": { + "Type": "WeightedRoundRobin" + }, + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 5666 + }, + { + "Host": "localhost", + "Port": 5667 + }, + { + "Host": "localhost", + "Port": 5668 + }, + { + "Host": "localhost", + "Port": 5669 + }, + { + "Host": "localhost", + "Port": 5670 + } + ] + } + ] +} \ No newline at end of file diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..6e795b60 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №2 "Балансировка нагрузки" + Вариант №10 "Учебный Курс" + Выполнена Марининым Андреем 6511 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..2d922c05 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7121/study-course" } diff --git a/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj new file mode 100644 index 00000000..80a5964a --- /dev/null +++ b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj @@ -0,0 +1,26 @@ + + + + + + Exe + net8.0 + enable + enable + true + f765995e-9d3a-45b8-96dc-a5dc50cd0089 + + + + + + + + + + + + + + + diff --git a/CloudDevelopment.AppHost/Program.cs b/CloudDevelopment.AppHost/Program.cs new file mode 100644 index 00000000..4449c088 --- /dev/null +++ b/CloudDevelopment.AppHost/Program.cs @@ -0,0 +1,19 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("course-cache") + .WithRedisInsight(containerName: "course-insight"); +var gateway = builder.AddProject("api-gateway"); + +for(var i = 0; i < 5; i++) +{ + var service = builder.AddProject($"service-api-{i}", launchProfileName:null) + .WithReference(cache, "RedisCache") + .WaitFor(cache) + .WithHttpsEndpoint(port:5666+i); + gateway.WaitFor(service).WithReference(service); +} + +builder.AddProject("client") + .WaitFor(gateway); + +builder.Build().Run(); diff --git a/CloudDevelopment.AppHost/Properties/launchSettings.json b/CloudDevelopment.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..0f3fea29 --- /dev/null +++ b/CloudDevelopment.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:17010;http://localhost:15047", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21117", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22258" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15047", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19001", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20248" + } + } + } +} diff --git a/CloudDevelopment.AppHost/appsettings.Development.json b/CloudDevelopment.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CloudDevelopment.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CloudDevelopment.AppHost/appsettings.json b/CloudDevelopment.AppHost/appsettings.json new file mode 100644 index 00000000..31c092aa --- /dev/null +++ b/CloudDevelopment.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj b/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj new file mode 100644 index 00000000..6c036a13 --- /dev/null +++ b/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/CloudDevelopment.ServiceDefaults/Extensions.cs b/CloudDevelopment.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..c7fceef1 --- /dev/null +++ b/CloudDevelopment.ServiceDefaults/Extensions.cs @@ -0,0 +1,120 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.ServiceDiscovery; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace CloudDevelopment.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 +{ + 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() + // 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("/health"); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks("/alive", new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..473ab146 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,6 +5,17 @@ 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}") = "Service.Api", "Service.Api\Service.Api.csproj", "{8D0E7890-C6A6-4CB1-90E8-1C7672C6171A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.AppHost", "CloudDevelopment.AppHost\CloudDevelopment.AppHost.csproj", "{B23EF7D0-C8C5-454D-A02C-A20F5076A90B}" + ProjectSection(ProjectDependencies) = postProject + {AE7EEA74-2FE0-136F-D797-854FD87E022A} = {AE7EEA74-2FE0-136F-D797-854FD87E022A} + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.ServiceDefaults", "CloudDevelopment.ServiceDefaults\CloudDevelopment.ServiceDefaults.csproj", "{C7312DF2-3D8D-4908-96B0-2987647254B3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{9C11CB6C-036E-4842-808F-4E4FAB8DA7D8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +26,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 + {8D0E7890-C6A6-4CB1-90E8-1C7672C6171A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8D0E7890-C6A6-4CB1-90E8-1C7672C6171A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8D0E7890-C6A6-4CB1-90E8-1C7672C6171A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8D0E7890-C6A6-4CB1-90E8-1C7672C6171A}.Release|Any CPU.Build.0 = Release|Any CPU + {B23EF7D0-C8C5-454D-A02C-A20F5076A90B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B23EF7D0-C8C5-454D-A02C-A20F5076A90B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B23EF7D0-C8C5-454D-A02C-A20F5076A90B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B23EF7D0-C8C5-454D-A02C-A20F5076A90B}.Release|Any CPU.Build.0 = Release|Any CPU + {C7312DF2-3D8D-4908-96B0-2987647254B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C7312DF2-3D8D-4908-96B0-2987647254B3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C7312DF2-3D8D-4908-96B0-2987647254B3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C7312DF2-3D8D-4908-96B0-2987647254B3}.Release|Any CPU.Build.0 = Release|Any CPU + {9C11CB6C-036E-4842-808F-4E4FAB8DA7D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9C11CB6C-036E-4842-808F-4E4FAB8DA7D8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9C11CB6C-036E-4842-808F-4E4FAB8DA7D8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9C11CB6C-036E-4842-808F-4E4FAB8DA7D8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/README.md b/README.md index dcaa5eb7..abd827f0 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,8 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](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). - +Современные технологии разработки программного обеспечения +Вариант 10 Учебный курс +Лабораторная работа №2 + +В рамках второй лабораторной работы было реализовано: +1. Оркестрацию на запуск нескольких реплик сервиса генерации, +2. Апи гейтвей на основе Ocelot, +3. Алгоритм балансировки нагрузки WeightedRoundRobin. diff --git a/Service.Api/Entities/StudyCourse.cs b/Service.Api/Entities/StudyCourse.cs new file mode 100644 index 00000000..cae5e56e --- /dev/null +++ b/Service.Api/Entities/StudyCourse.cs @@ -0,0 +1,68 @@ +using System.Text.Json.Serialization; +namespace Service.Api.Entities; + +/// +/// Учебный курс +/// +public class StudyCourse +{ + /// + /// Идентификатор курса + /// + [JsonPropertyName("id")] + public required int Id { get; set; } + + /// + /// Название курса + /// + [JsonPropertyName("courseName")] + public required string CourseName { get; set; } + + /// + /// Полное имя преподавателя, ведущего курс + /// + [JsonPropertyName("teacherFullName")] + public required string TeacherFullName { get; set; } + + /// + /// Дата начала курса + /// + [JsonPropertyName("startDate")] + public DateOnly? StartDate { get; set; } + + /// + /// Дата окончания курса + /// + [JsonPropertyName("endDate")] + public DateOnly? EndDate { get; set; } + + /// + /// Максимальное количество студентов, которые могут быть записаны на курс + /// + [JsonPropertyName("maxStudents")] + public required int MaxStudents { get; set; } + + /// + /// Текущее количество студентов, записанных на курс + /// + [JsonPropertyName("currentStudents")] + public required int CurrentStudents { get; set; } + + /// + /// Указывает, выдается ли сертификат после успешного завершения курса + /// + [JsonPropertyName("givesCertificate")] + public required bool GivesCertificate { get; set; } + + /// + /// Стоимость курса. + /// + [JsonPropertyName("cost")] + public required decimal Cost { get; set; } + + /// + /// Рейтинг курса от 1 до 5. + /// + [JsonPropertyName("rating")] + public int? Rating { get; set; } +} diff --git a/Service.Api/Generator/GeneratorService.cs b/Service.Api/Generator/GeneratorService.cs new file mode 100644 index 00000000..61f2183f --- /dev/null +++ b/Service.Api/Generator/GeneratorService.cs @@ -0,0 +1,54 @@ +using Microsoft.Extensions.Caching.Distributed; +using Service.Api.Entities; +using System.Text.Json; + +namespace Service.Api.Generator; + +public class GeneratorService(IDistributedCache _cache, IConfiguration _configuration, ILogger _logger) : IGeneratorService +{ + private readonly TimeSpan _cacheExpiration = TimeSpan.FromSeconds(_configuration.GetSection("Cache").GetValue("CacheExpiration", 3600)); + public async Task ProcessCourse(int id) + { + _logger.LogInformation("Processing course with ID: {CourseId}", id); + try + { + _logger.LogInformation("Attempting to retrieve course from cache with ID: {CourseId}", id); + var course = await RetrieveFromCache(id); + if (course != null) + { + _logger.LogInformation("Course with ID: {CourseId} retrieved from cache", id); + return course; + } + _logger.LogInformation("Course with ID: {CourseId} not found in cache, generating new course", id); + course = StudyCoureGenerator.GenerateCourse(id); + _logger.LogInformation("Populating cache with course {id}", id); + await SetCache(course); + return course; + } + catch (Exception ex) + { + _logger.LogError(ex, "An error occurred while processing course with ID: {id}", id); + throw; + } + } + private async Task RetrieveFromCache(int id) + { + var json = await _cache.GetStringAsync(id.ToString()); + if (!string.IsNullOrEmpty(json)) + { + return JsonSerializer.Deserialize(json); + } + _logger.LogInformation("Course with ID: {CourseId} not found in cache", id); + return null; + } + private async Task SetCache(StudyCourse course) + { + var json = JsonSerializer.Serialize(course); + var options = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheExpiration + }; + await _cache.SetStringAsync(course.Id.ToString(), json, options); + _logger.LogInformation("Course with ID: {CourseId} stored in cache with expiration of {Expiration}", course.Id, _cacheExpiration); + } +} \ No newline at end of file diff --git a/Service.Api/Generator/IGeneratorService.cs b/Service.Api/Generator/IGeneratorService.cs new file mode 100644 index 00000000..9dd08396 --- /dev/null +++ b/Service.Api/Generator/IGeneratorService.cs @@ -0,0 +1,16 @@ +using Service.Api.Entities; + +namespace Service.Api.Generator; + +/// +/// Интерфейс для запуска юзкейса по обработке учебных курсов +/// +public interface IGeneratorService +{ + /// + /// Обработка запроса на генерацию учебного курса. + /// + /// ИД + /// + public Task ProcessCourse(int id); +} diff --git a/Service.Api/Generator/StudyCoureGenerator.cs b/Service.Api/Generator/StudyCoureGenerator.cs new file mode 100644 index 00000000..5aae0903 --- /dev/null +++ b/Service.Api/Generator/StudyCoureGenerator.cs @@ -0,0 +1,38 @@ +using Bogus; +using Service.Api.Entities; +namespace Service.Api.Generator; + +public static class StudyCoureGenerator +{ + private static readonly List _courseNames = ["English", "Spanish", "Hand Craft", "Math", "Chinese", "Yoga"]; + + private const int MaxRating = 5; + private const int MinRating = 1; + private const int DigitsRound = 2; + private const int MinCost = 0; + private const int MaxCost = 10000000; + private const int MinStudents = 0; + private const int MaxStudents = 1000; + private static readonly DateOnly _minDate = new (2020, 1, 1); + private static readonly DateOnly _maxDate = new(2030, 1, 1); + private const int MaxYearsForward = 5; + + private static Faker _faker = new Faker("en") + .RuleFor(s => s.TeacherFullName, f => $"{f.PickRandom(f.Person.FirstName)} {f.PickRandom(f.Person.LastName)}") + .RuleFor(s => s.CourseName, f => f.PickRandom(_courseNames)) + .RuleFor(s => s.StartDate, f => f.Date.BetweenDateOnly(_minDate, _maxDate)) + .RuleFor(s => s.EndDate, (f, s) => f.Date.FutureDateOnly(MaxYearsForward, s.StartDate)) + .RuleFor(s => s.GivesCertificate, f => f.Random.Bool()) + .RuleFor(s => s.Cost, f => Math.Round(f.Random.Decimal(MinCost, MaxCost), DigitsRound)) + .RuleFor(s => s.MaxStudents, f => f.Random.Int(MinStudents, MaxStudents)) + .RuleFor(s => s.CurrentStudents, (f, s) => f.Random.Int(MinStudents, s.MaxStudents)) + .RuleFor(s => s.Rating, f => f.Random.Int(MinRating, MaxRating)); + + public static StudyCourse GenerateCourse(int id) + { + var course = _faker.Generate(); + course.Id = id; + return course; + } + +} diff --git a/Service.Api/Program.cs b/Service.Api/Program.cs new file mode 100644 index 00000000..5f891d3b --- /dev/null +++ b/Service.Api/Program.cs @@ -0,0 +1,13 @@ +using CloudDevelopment.ServiceDefaults; +using Service.Api.Generator; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("RedisCache"); +builder.Services.AddScoped(); +var app = builder.Build(); + +app.MapDefaultEndpoints(); +app.MapGet("/api/study-course", (IGeneratorService service, int id) => service.ProcessCourse(id)); +app.Run(); diff --git a/Service.Api/Properties/launchSettings.json b/Service.Api/Properties/launchSettings.json new file mode 100644 index 00000000..192ad868 --- /dev/null +++ b/Service.Api/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:52805", + "sslPort": 44383 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5241", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7125;http://localhost:5241", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Service.Api/Service.Api.csproj b/Service.Api/Service.Api.csproj new file mode 100644 index 00000000..a1376048 --- /dev/null +++ b/Service.Api/Service.Api.csproj @@ -0,0 +1,18 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + diff --git a/Service.Api/appsettings.Development.json b/Service.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Service.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Service.Api/appsettings.json b/Service.Api/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/Service.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +}