From 7f16b3bbabe50713b4b6bcc0e5d6fc9fa9e844d2 Mon Sep 17 00:00:00 2001 From: Andrei Date: Fri, 6 Mar 2026 19:26:41 +0400 Subject: [PATCH 1/9] =?UTF-8?q?=D0=A0=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D0=BB=20=D1=81=D1=83=D1=89=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D1=8C,=20=D0=B3=D0=B5=D0=BD=D0=B5=D1=80=D0=B0=D1=82=D0=BE?= =?UTF-8?q?=D1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CloudDevelopment.AppHost.csproj | 23 ++++ CloudDevelopment.AppHost/Program.cs | 8 ++ .../Properties/launchSettings.json | 29 +++++ .../appsettings.Development.json | 8 ++ CloudDevelopment.AppHost/appsettings.json | 9 ++ .../CloudDevelopment.ServiceDefaults.csproj | 22 ++++ .../Extensions.cs | 120 ++++++++++++++++++ CloudDevelopment.sln | 21 +++ Service.Api/Entities/StudyCourse.cs | 68 ++++++++++ Service.Api/Generator/GeneratorService.cs | 58 +++++++++ Service.Api/Generator/IGeneratorService.cs | 16 +++ Service.Api/Generator/StudyCoureGenerator.cs | 43 +++++++ Service.Api/Program.cs | 12 ++ Service.Api/Properties/launchSettings.json | 38 ++++++ Service.Api/Service.Api.csproj | 18 +++ Service.Api/appsettings.Development.json | 8 ++ Service.Api/appsettings.json | 9 ++ 17 files changed, 510 insertions(+) create mode 100644 CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj create mode 100644 CloudDevelopment.AppHost/Program.cs create mode 100644 CloudDevelopment.AppHost/Properties/launchSettings.json create mode 100644 CloudDevelopment.AppHost/appsettings.Development.json create mode 100644 CloudDevelopment.AppHost/appsettings.json create mode 100644 CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj create mode 100644 CloudDevelopment.ServiceDefaults/Extensions.cs create mode 100644 Service.Api/Entities/StudyCourse.cs create mode 100644 Service.Api/Generator/GeneratorService.cs create mode 100644 Service.Api/Generator/IGeneratorService.cs create mode 100644 Service.Api/Generator/StudyCoureGenerator.cs create mode 100644 Service.Api/Program.cs create mode 100644 Service.Api/Properties/launchSettings.json create mode 100644 Service.Api/Service.Api.csproj create mode 100644 Service.Api/appsettings.Development.json create mode 100644 Service.Api/appsettings.json diff --git a/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj new file mode 100644 index 00000000..066c0137 --- /dev/null +++ b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj @@ -0,0 +1,23 @@ + + + + + + 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..929d6e4f --- /dev/null +++ b/CloudDevelopment.AppHost/Program.cs @@ -0,0 +1,8 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var service = builder.AddProject("service-api"); + +builder.AddProject("client") + .WaitFor(service); + +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..b9c9beba 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,6 +5,15 @@ 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 Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +24,18 @@ 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 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Service.Api/Entities/StudyCourse.cs b/Service.Api/Entities/StudyCourse.cs new file mode 100644 index 00000000..da653bae --- /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 int Id { get; set; } + + /// + /// Название курса + /// + [JsonPropertyName("courseName")] + public string? CourseName { get; set; } + + /// + /// Полное имя преподавателя, ведущего курс + /// + [JsonPropertyName("teacherFullName")] + public string? TeacherFullName { get; set; } + + /// + /// Дата начала курса + /// + [JsonPropertyName("startDate")] + public DateOnly? StartDate { get; set; } + + /// + /// Дата окончания курса + /// + [JsonPropertyName("endDate")] + public DateOnly? EndDate { get; set; } + + /// + /// Максимальное количество студентов, которые могут быть записаны на курс + /// + [JsonPropertyName("maxStudents")] + public int? MaxStudents { get; set; } + + /// + /// Текущее количество студентов, записанных на курс + /// + [JsonPropertyName("currentStudents")] + public int? CurrentStudents { get; set; } + + /// + /// Указывает, выдается ли сертификат после успешного завершения курса + /// + [JsonPropertyName("givesCertificate")] + public bool? GivesCertificate { get; set; } + + /// + /// Стоимость курса. + /// + [JsonPropertyName("cost")] + public 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..ebd09541 --- /dev/null +++ b/Service.Api/Generator/GeneratorService.cs @@ -0,0 +1,58 @@ +using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; +using System; +using Service.Api.Entities; +using Microsoft.Extensions.Configuration; + +namespace Service.Api.Generator; + +public class GeneratorService(IDistributedCache _cache, IConfiguration _configuration, ILogger _logger) : IGeneratorService +{ + private readonly TimeSpan _cacheExpiration = int.TryParse(_configuration["CacheExpiration"], out var seconds) + ? TimeSpan.FromSeconds(seconds) + : TimeSpan.FromSeconds(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 PopulateCache(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)) + { + _logger.LogInformation("Course with ID: {CourseId} not found in cache", id); + return null; + } + return JsonSerializer.Deserialize(json); + } + private async Task PopulateCache(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..778143e4 --- /dev/null +++ b/Service.Api/Generator/StudyCoureGenerator.cs @@ -0,0 +1,43 @@ +using Bogus; +using Service.Api.Entities; +namespace Service.Api.Generator; + +public static class StudyCoureGenerator +{ + private static readonly List _firstNames = new(["Donald", "Kanye", "Carl", "Bob", "Alice", "Albert", "Sam", "Andrew"]); + + private static readonly List _secondNames = new(["Smith", "Trump", "Fed", "Stone", "Johnson", "Williams", "Klinton", "Morgan"]); + + private static readonly List _patronymics = new(["Alex", "Bobby", "Steave", "Michael", "John", "Dan", "Ban", "George"]); + + private static readonly List _courseNames = new(["English", "Spanish", "Hand Craft", "Math", "Chinese", "Yoga"]); + + private static readonly int _maxRating = 5; + private static readonly int _minRating = 1; + private static readonly int _digitsRound = 2; + private static readonly int _minCost = 0; + private static readonly int _maxCost = 10000000; + private static readonly int _minStudents = 0; + private static readonly int _maxStudents = 1000; + private static DateOnly _minDate = new (2020, 1, 1); + private static DateOnly _maxDate = new(2030, 1, 1); + private static int _maxYearsForward = 5; + + private static Faker _faker = new Faker("en") + .RuleFor(s => s.TeacherFullName, f => $"{f.PickRandom(_firstNames)} {f.PickRandom(_patronymics)} {f.PickRandom(_secondNames)}") + .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 ?? _maxStudents)); + + 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..5e9812b3 --- /dev/null +++ b/Service.Api/Program.cs @@ -0,0 +1,12 @@ +using CloudDevelopment.ServiceDefaults; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +app.MapGet("/", () => "Hello World!"); + +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": "*" +} From 72510b083ca3cf1a73aa673bebf741347011cae2 Mon Sep 17 00:00:00 2001 From: andrM66 <2021-00684@students.ssau.ru> Date: Fri, 6 Mar 2026 20:31:55 +0400 Subject: [PATCH 2/9] Update README.md --- README.md | 139 +++++------------------------------------------------- 1 file changed, 12 insertions(+), 127 deletions(-) diff --git a/README.md b/README.md index dcaa5eb7..c5475255 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,13 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](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 Учебный курс +Лабораторная работа №1 +1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов +2. Реализовано: +Сущность: Service.Api.Entities.StudyCourse +Сервис генерации данных: Service.Api.Generator.StudyCourseGenerator +Сервис кэширования: Service.Api.Generator.GeneratorService +Интерфейс: +image +image +image From f74a6ad9592eaf606f8b82aa7bc8baf053039b0f Mon Sep 17 00:00:00 2001 From: Andrei Date: Fri, 6 Mar 2026 20:32:14 +0400 Subject: [PATCH 3/9] =?UTF-8?q?=D0=9A=D1=8D=D1=88=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Client.Wasm/Components/StudentCard.razor | 8 ++++---- Client.Wasm/wwwroot/appsettings.json | 2 +- .../CloudDevelopment.AppHost.csproj | 5 +++-- CloudDevelopment.AppHost/Program.cs | 7 ++++++- Service.Api/Generator/StudyCoureGenerator.cs | 3 ++- Service.Api/Program.cs | 14 +++++++++++--- 6 files changed, 27 insertions(+), 12 deletions(-) diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..9fad2718 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 "Кэширование" + Вариант №10 "Учебный Курс" + Выполнена Марининым Андреем 6511 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..02d06f53 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7125/study-course" } diff --git a/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj index 066c0137..480c2f4d 100644 --- a/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj +++ b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj @@ -1,4 +1,4 @@ - + @@ -13,11 +13,12 @@ + - + diff --git a/CloudDevelopment.AppHost/Program.cs b/CloudDevelopment.AppHost/Program.cs index 929d6e4f..f3cd8fc9 100644 --- a/CloudDevelopment.AppHost/Program.cs +++ b/CloudDevelopment.AppHost/Program.cs @@ -1,6 +1,11 @@ var builder = DistributedApplication.CreateBuilder(args); -var service = builder.AddProject("service-api"); +var cache = builder.AddRedis("course-cache") + .WithRedisInsight(containerName: "course-insight"); + +var service = builder.AddProject("service-api") + .WithReference(cache, "RedisCache") + .WaitFor(cache); builder.AddProject("client") .WaitFor(service); diff --git a/Service.Api/Generator/StudyCoureGenerator.cs b/Service.Api/Generator/StudyCoureGenerator.cs index 778143e4..7c3cda64 100644 --- a/Service.Api/Generator/StudyCoureGenerator.cs +++ b/Service.Api/Generator/StudyCoureGenerator.cs @@ -31,7 +31,8 @@ public static class StudyCoureGenerator .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 ?? _maxStudents)); + .RuleFor(s => s.CurrentStudents, (f, s) => f.Random.Int(_minStudents, s.MaxStudents ?? _maxStudents)) + .RuleFor(s => s.Rating, f => f.Random.Int(_minRating, _maxRating)); public static StudyCourse GenerateCourse(int id) { diff --git a/Service.Api/Program.cs b/Service.Api/Program.cs index 5e9812b3..9c23b62b 100644 --- a/Service.Api/Program.cs +++ b/Service.Api/Program.cs @@ -1,12 +1,20 @@ using CloudDevelopment.ServiceDefaults; +using Service.Api.Generator; var builder = WebApplication.CreateBuilder(args); builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("RedisCache"); +builder.Services.AddScoped(); +builder.Services.AddCors(options => options.AddDefaultPolicy(policy => +{ + policy.AllowAnyOrigin(); + policy.AllowAnyMethod(); + policy.AllowAnyHeader(); +})); var app = builder.Build(); app.MapDefaultEndpoints(); - -app.MapGet("/", () => "Hello World!"); - +app.MapGet("/study-course", (IGeneratorService service, int id) => service.ProcessCourse(id)); +app.UseCors(); app.Run(); From dc55efc77796e6fd7f9ef1ee39ff5321d64eda52 Mon Sep 17 00:00:00 2001 From: Andrei Date: Fri, 6 Mar 2026 20:34:20 +0400 Subject: [PATCH 4/9] =?UTF-8?q?=D1=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 140 +++++------------------------------------------------- 1 file changed, 12 insertions(+), 128 deletions(-) diff --git a/README.md b/README.md index dcaa5eb7..3dbeff28 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,12 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](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 Учебный курс +Лабораторная работа №1 +1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов +2. Реализовано: +Сущность: Service.Api.Entities.StudyCourse +Сервис генерации данных: Service.Api.Generator.StudyCourseGenerator +Сервис кэширования: Service.Api.Generator.GeneratorService +Интерфейс: +image +image +image \ No newline at end of file From 3d8da55f4b3bd05eaf802fbec4c07258f50811d3 Mon Sep 17 00:00:00 2001 From: andrM66 <2021-00684@students.ssau.ru> Date: Fri, 6 Mar 2026 20:37:36 +0400 Subject: [PATCH 5/9] Update README.md --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3dbeff28..1d8b03e3 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,14 @@ Лабораторная работа №1 1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов 2. Реализовано: + Сущность: Service.Api.Entities.StudyCourse + Сервис генерации данных: Service.Api.Generator.StudyCourseGenerator + Сервис кэширования: Service.Api.Generator.GeneratorService + Интерфейс: image image -image \ No newline at end of file +image From 4cdb353dcaa8a80aeeb210fda98ac577ee8e7a82 Mon Sep 17 00:00:00 2001 From: Andrei Date: Sat, 14 Mar 2026 16:53:29 +0400 Subject: [PATCH 6/9] fixes --- .../CloudDevelopment.AppHost.csproj | 7 ++-- Service.Api/Entities/StudyCourse.cs | 14 +++---- Service.Api/Generator/GeneratorService.cs | 20 ++++----- Service.Api/Generator/StudyCoureGenerator.cs | 42 ++++++++----------- 4 files changed, 37 insertions(+), 46 deletions(-) diff --git a/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj index 480c2f4d..17b95388 100644 --- a/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj +++ b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj @@ -1,6 +1,6 @@  - + Exe @@ -12,8 +12,9 @@ - - + + + diff --git a/Service.Api/Entities/StudyCourse.cs b/Service.Api/Entities/StudyCourse.cs index da653bae..cae5e56e 100644 --- a/Service.Api/Entities/StudyCourse.cs +++ b/Service.Api/Entities/StudyCourse.cs @@ -10,19 +10,19 @@ public class StudyCourse /// Идентификатор курса /// [JsonPropertyName("id")] - public int Id { get; set; } + public required int Id { get; set; } /// /// Название курса /// [JsonPropertyName("courseName")] - public string? CourseName { get; set; } + public required string CourseName { get; set; } /// /// Полное имя преподавателя, ведущего курс /// [JsonPropertyName("teacherFullName")] - public string? TeacherFullName { get; set; } + public required string TeacherFullName { get; set; } /// /// Дата начала курса @@ -40,25 +40,25 @@ public class StudyCourse /// Максимальное количество студентов, которые могут быть записаны на курс /// [JsonPropertyName("maxStudents")] - public int? MaxStudents { get; set; } + public required int MaxStudents { get; set; } /// /// Текущее количество студентов, записанных на курс /// [JsonPropertyName("currentStudents")] - public int? CurrentStudents { get; set; } + public required int CurrentStudents { get; set; } /// /// Указывает, выдается ли сертификат после успешного завершения курса /// [JsonPropertyName("givesCertificate")] - public bool? GivesCertificate { get; set; } + public required bool GivesCertificate { get; set; } /// /// Стоимость курса. /// [JsonPropertyName("cost")] - public decimal? Cost { get; set; } + public required decimal Cost { get; set; } /// /// Рейтинг курса от 1 до 5. diff --git a/Service.Api/Generator/GeneratorService.cs b/Service.Api/Generator/GeneratorService.cs index ebd09541..61f2183f 100644 --- a/Service.Api/Generator/GeneratorService.cs +++ b/Service.Api/Generator/GeneratorService.cs @@ -1,16 +1,12 @@ using Microsoft.Extensions.Caching.Distributed; -using System.Text.Json; -using System; using Service.Api.Entities; -using Microsoft.Extensions.Configuration; +using System.Text.Json; namespace Service.Api.Generator; public class GeneratorService(IDistributedCache _cache, IConfiguration _configuration, ILogger _logger) : IGeneratorService { - private readonly TimeSpan _cacheExpiration = int.TryParse(_configuration["CacheExpiration"], out var seconds) - ? TimeSpan.FromSeconds(seconds) - : TimeSpan.FromSeconds(3600); + 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); @@ -26,7 +22,7 @@ public async Task ProcessCourse(int id) _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 PopulateCache(course); + await SetCache(course); return course; } catch (Exception ex) @@ -38,14 +34,14 @@ public async Task ProcessCourse(int id) private async Task RetrieveFromCache(int id) { var json = await _cache.GetStringAsync(id.ToString()); - if(string.IsNullOrEmpty(json)) + if (!string.IsNullOrEmpty(json)) { - _logger.LogInformation("Course with ID: {CourseId} not found in cache", id); - return null; + return JsonSerializer.Deserialize(json); } - return JsonSerializer.Deserialize(json); + _logger.LogInformation("Course with ID: {CourseId} not found in cache", id); + return null; } - private async Task PopulateCache(StudyCourse course) + private async Task SetCache(StudyCourse course) { var json = JsonSerializer.Serialize(course); var options = new DistributedCacheEntryOptions diff --git a/Service.Api/Generator/StudyCoureGenerator.cs b/Service.Api/Generator/StudyCoureGenerator.cs index 7c3cda64..f87fee19 100644 --- a/Service.Api/Generator/StudyCoureGenerator.cs +++ b/Service.Api/Generator/StudyCoureGenerator.cs @@ -4,35 +4,29 @@ namespace Service.Api.Generator; public static class StudyCoureGenerator { - private static readonly List _firstNames = new(["Donald", "Kanye", "Carl", "Bob", "Alice", "Albert", "Sam", "Andrew"]); - - private static readonly List _secondNames = new(["Smith", "Trump", "Fed", "Stone", "Johnson", "Williams", "Klinton", "Morgan"]); - - private static readonly List _patronymics = new(["Alex", "Bobby", "Steave", "Michael", "John", "Dan", "Ban", "George"]); - - private static readonly List _courseNames = new(["English", "Spanish", "Hand Craft", "Math", "Chinese", "Yoga"]); - - private static readonly int _maxRating = 5; - private static readonly int _minRating = 1; - private static readonly int _digitsRound = 2; - private static readonly int _minCost = 0; - private static readonly int _maxCost = 10000000; - private static readonly int _minStudents = 0; - private static readonly int _maxStudents = 1000; - private static DateOnly _minDate = new (2020, 1, 1); - private static DateOnly _maxDate = new(2030, 1, 1); - private static int _maxYearsForward = 5; + 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(_firstNames)} {f.PickRandom(_patronymics)} {f.PickRandom(_secondNames)}") + .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.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 ?? _maxStudents)) - .RuleFor(s => s.Rating, f => f.Random.Int(_minRating, _maxRating)); + .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) { From 2812c7283dcb2f9f610e4127c3a1f8caaab03d34 Mon Sep 17 00:00:00 2001 From: Andrei Date: Thu, 2 Apr 2026 19:01:45 +0400 Subject: [PATCH 7/9] =?UTF-8?q?gateway=20+=20=D0=B1=D0=B0=D0=BB=D0=B0?= =?UTF-8?q?=D0=BD=D1=81=D0=B8=D1=80=D0=BE=D0=B2=D1=89=D0=B8=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Api.Gateway/Api.Gateway.csproj | 19 ++++++++ Api.Gateway/Balancing/WeightedRoundRobin.cs | 43 +++++++++++++++++++ Api.Gateway/Program.cs | 40 +++++++++++++++++ Api.Gateway/Properties/launchSettings.json | 38 ++++++++++++++++ Api.Gateway/appsettings.Development.json | 8 ++++ Api.Gateway/appsettings.json | 10 +++++ Api.Gateway/ocelot.json | 35 +++++++++++++++ Client.Wasm/Components/StudentCard.razor | 2 +- Client.Wasm/wwwroot/appsettings.json | 2 +- .../CloudDevelopment.AppHost.csproj | 1 + CloudDevelopment.AppHost/Program.cs | 12 ++++-- CloudDevelopment.sln | 6 +++ Service.Api/Generator/StudyCoureGenerator.cs | 2 +- Service.Api/Program.cs | 9 +--- 14 files changed, 213 insertions(+), 14 deletions(-) create mode 100644 Api.Gateway/Api.Gateway.csproj create mode 100644 Api.Gateway/Balancing/WeightedRoundRobin.cs create mode 100644 Api.Gateway/Program.cs create mode 100644 Api.Gateway/Properties/launchSettings.json create mode 100644 Api.Gateway/appsettings.Development.json create mode 100644 Api.Gateway/appsettings.json create mode 100644 Api.Gateway/ocelot.json 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 9fad2718..6e795b60 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,7 +4,7 @@ - Номер №1 "Кэширование" + Номер №2 "Балансировка нагрузки" Вариант №10 "Учебный Курс" Выполнена Марининым Андреем 6511 Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index 02d06f53..2d922c05 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "https://localhost:7125/study-course" + "BaseAddress": "https://localhost:7121/study-course" } diff --git a/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj index 17b95388..80a5964a 100644 --- a/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj +++ b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj @@ -18,6 +18,7 @@ + diff --git a/CloudDevelopment.AppHost/Program.cs b/CloudDevelopment.AppHost/Program.cs index f3cd8fc9..4449c088 100644 --- a/CloudDevelopment.AppHost/Program.cs +++ b/CloudDevelopment.AppHost/Program.cs @@ -2,12 +2,18 @@ var cache = builder.AddRedis("course-cache") .WithRedisInsight(containerName: "course-insight"); +var gateway = builder.AddProject("api-gateway"); -var service = builder.AddProject("service-api") +for(var i = 0; i < 5; i++) +{ + var service = builder.AddProject($"service-api-{i}", launchProfileName:null) .WithReference(cache, "RedisCache") - .WaitFor(cache); + .WaitFor(cache) + .WithHttpsEndpoint(port:5666+i); + gateway.WaitFor(service).WithReference(service); +} builder.AddProject("client") - .WaitFor(service); + .WaitFor(gateway); builder.Build().Run(); diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index b9c9beba..473ab146 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -14,6 +14,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.AppHost", 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 @@ -36,6 +38,10 @@ Global {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/Service.Api/Generator/StudyCoureGenerator.cs b/Service.Api/Generator/StudyCoureGenerator.cs index f87fee19..5aae0903 100644 --- a/Service.Api/Generator/StudyCoureGenerator.cs +++ b/Service.Api/Generator/StudyCoureGenerator.cs @@ -17,7 +17,7 @@ public static class StudyCoureGenerator private static readonly DateOnly _maxDate = new(2030, 1, 1); private const int MaxYearsForward = 5; - private static Faker _faker = new Faker("en") + 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)) diff --git a/Service.Api/Program.cs b/Service.Api/Program.cs index 9c23b62b..5f891d3b 100644 --- a/Service.Api/Program.cs +++ b/Service.Api/Program.cs @@ -6,15 +6,8 @@ builder.AddServiceDefaults(); builder.AddRedisDistributedCache("RedisCache"); builder.Services.AddScoped(); -builder.Services.AddCors(options => options.AddDefaultPolicy(policy => -{ - policy.AllowAnyOrigin(); - policy.AllowAnyMethod(); - policy.AllowAnyHeader(); -})); var app = builder.Build(); app.MapDefaultEndpoints(); -app.MapGet("/study-course", (IGeneratorService service, int id) => service.ProcessCourse(id)); -app.UseCors(); +app.MapGet("/api/study-course", (IGeneratorService service, int id) => service.ProcessCourse(id)); app.Run(); From c92978c614e883a5e356c5cb803f5e6fc7f3f184 Mon Sep 17 00:00:00 2001 From: andrM66 <2021-00684@students.ssau.ru> Date: Thu, 2 Apr 2026 19:11:21 +0400 Subject: [PATCH 8/9] Update README.md --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 1d8b03e3..14da7eb4 100644 --- a/README.md +++ b/README.md @@ -14,3 +14,15 @@ image image image + + + + +Современные технологии разработки программного обеспечения Вариант 10 Учебный курс Лабораторная работа №2 + + +В рамках второй лабораторной работы было реализовано: + +1. Оркестрацию на запуск нескольких реплик сервиса генерации, +2. Апи гейтвей на основе Ocelot, +3. Алгоритм балансировки нагрузки WeightedRoundRobin. From 2b6de2ddebe49661b24c70f7cd59257aa8bd7ede Mon Sep 17 00:00:00 2001 From: andrM66 <2021-00684@students.ssau.ru> Date: Thu, 2 Apr 2026 19:12:40 +0400 Subject: [PATCH 9/9] Update README to reflect changes in lab work Removed details about Lab 1 and added information about Lab 2, including orchestration, API gateway, and load balancing algorithm. --- README.md | 22 +--------------------- 1 file changed, 1 insertion(+), 21 deletions(-) diff --git a/README.md b/README.md index 14da7eb4..abd827f0 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,8 @@ Современные технологии разработки программного обеспечения Вариант 10 Учебный курс -Лабораторная работа №1 -1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов -2. Реализовано: - -Сущность: Service.Api.Entities.StudyCourse - -Сервис генерации данных: Service.Api.Generator.StudyCourseGenerator - -Сервис кэширования: Service.Api.Generator.GeneratorService - -Интерфейс: -image -image -image - - - - -Современные технологии разработки программного обеспечения Вариант 10 Учебный курс Лабораторная работа №2 - +Лабораторная работа №2 В рамках второй лабораторной работы было реализовано: - 1. Оркестрацию на запуск нескольких реплик сервиса генерации, 2. Апи гейтвей на основе Ocelot, 3. Алгоритм балансировки нагрузки WeightedRoundRobin.