From 0bde0541e34176ad21312a8667cc424a5509d7fa Mon Sep 17 00:00:00 2001 From: Daryaskhrv Date: Thu, 19 Feb 2026 22:16:27 +0400 Subject: [PATCH 1/8] lab1 --- Client.Wasm/Components/StudentCard.razor | 8 +- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.sln | 28 +++- CourseApp.Api/Controllers/CourseController.cs | 22 ++++ CourseApp.Api/CourseApp.Api.csproj | 20 +++ CourseApp.Api/Program.cs | 39 ++++++ CourseApp.Api/Properties/launchSettings.json | 41 ++++++ CourseApp.Api/Services/CourseGenerator.cs | 40 ++++++ CourseApp.Api/Services/CourseService.cs | 51 ++++++++ CourseApp.Api/appsettings.Development.json | 8 ++ CourseApp.Api/appsettings.json | 12 ++ CourseApp.AppHost/AppHost.cs | 23 ++++ CourseApp.AppHost/CourseApp.AppHost.csproj | 22 ++++ .../Properties/launchSettings.json | 31 +++++ .../appsettings.Development.json | 8 ++ CourseApp.AppHost/appsettings.json | 9 ++ CourseApp.Domain/CourseApp.Domain.csproj | 9 ++ CourseApp.Domain/Entity/CourseApp.cs | 57 +++++++++ .../CourseApp.ServiceDefaults.csproj | 24 ++++ CourseApp.ServiceDefaults/Extensions.cs | 120 ++++++++++++++++++ 20 files changed, 567 insertions(+), 7 deletions(-) create mode 100644 CourseApp.Api/Controllers/CourseController.cs create mode 100644 CourseApp.Api/CourseApp.Api.csproj create mode 100644 CourseApp.Api/Program.cs create mode 100644 CourseApp.Api/Properties/launchSettings.json create mode 100644 CourseApp.Api/Services/CourseGenerator.cs create mode 100644 CourseApp.Api/Services/CourseService.cs create mode 100644 CourseApp.Api/appsettings.Development.json create mode 100644 CourseApp.Api/appsettings.json create mode 100644 CourseApp.AppHost/AppHost.cs create mode 100644 CourseApp.AppHost/CourseApp.AppHost.csproj create mode 100644 CourseApp.AppHost/Properties/launchSettings.json create mode 100644 CourseApp.AppHost/appsettings.Development.json create mode 100644 CourseApp.AppHost/appsettings.json create mode 100644 CourseApp.Domain/CourseApp.Domain.csproj create mode 100644 CourseApp.Domain/Entity/CourseApp.cs create mode 100644 CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj create mode 100644 CourseApp.ServiceDefaults/Extensions.cs diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..8acfba9d 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 Кэширование + Вариант №50 "Учебный курс" + Выполнена Сахаровой Дарьей 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..3e8284f6 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7068/api/course" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..c0634a98 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.11505.172 d18.3 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}") = "CourseApp.Domain", "CourseApp.Domain\CourseApp.Domain.csproj", "{8DB96A31-4C80-448B-8E97-33930E7DD01C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.Api", "CourseApp.Api\CourseApp.Api.csproj", "{3E70AD66-1A84-425D-8EAA-23B820F3A292}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.ServiceDefaults", "CourseApp.ServiceDefaults\CourseApp.ServiceDefaults.csproj", "{FA3F9ED2-E039-4168-AA5E-1E49E771AD99}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.AppHost", "CourseApp.AppHost\CourseApp.AppHost.csproj", "{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}" +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 + {8DB96A31-4C80-448B-8E97-33930E7DD01C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8DB96A31-4C80-448B-8E97-33930E7DD01C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8DB96A31-4C80-448B-8E97-33930E7DD01C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8DB96A31-4C80-448B-8E97-33930E7DD01C}.Release|Any CPU.Build.0 = Release|Any CPU + {3E70AD66-1A84-425D-8EAA-23B820F3A292}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3E70AD66-1A84-425D-8EAA-23B820F3A292}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3E70AD66-1A84-425D-8EAA-23B820F3A292}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3E70AD66-1A84-425D-8EAA-23B820F3A292}.Release|Any CPU.Build.0 = Release|Any CPU + {FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Release|Any CPU.Build.0 = Release|Any CPU + {8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CourseApp.Api/Controllers/CourseController.cs b/CourseApp.Api/Controllers/CourseController.cs new file mode 100644 index 00000000..ac561bba --- /dev/null +++ b/CourseApp.Api/Controllers/CourseController.cs @@ -0,0 +1,22 @@ +using CourseApp.Api.Services; +using CourseApp.Domain.Entity; +using Microsoft.AspNetCore.Mvc; + +namespace CourseApp.Api.Controllers; + +[ApiController] +[Route("api/[controller]")] +public class CourseController(CourseService _courseService) : ControllerBase +{ + /// + /// Получить курс по идентификатору + /// + /// Идентификатор курса + /// Информация о курсе + [HttpGet] + public async Task> Get(int id) + { + var course = await _courseService.GetCourseAsync(id); + return Ok(course); + } +} \ No newline at end of file diff --git a/CourseApp.Api/CourseApp.Api.csproj b/CourseApp.Api/CourseApp.Api.csproj new file mode 100644 index 00000000..4fec257e --- /dev/null +++ b/CourseApp.Api/CourseApp.Api.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + diff --git a/CourseApp.Api/Program.cs b/CourseApp.Api/Program.cs new file mode 100644 index 00000000..75c1fb87 --- /dev/null +++ b/CourseApp.Api/Program.cs @@ -0,0 +1,39 @@ +using CourseApp.Api.Services; +using CourseApp.ServiceDefaults; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddCors(options => +{ + options.AddPolicy("wasm", policy => + { + policy.AllowAnyOrigin() + .WithMethods("GET", "POST") + .WithHeaders("Content-Type"); + }); +}); + +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapDefaultEndpoints(); +app.UseHttpsRedirection(); +app.UseCors("wasm"); +app.UseAuthorization(); +app.MapControllers(); +app.Run(); \ No newline at end of file diff --git a/CourseApp.Api/Properties/launchSettings.json b/CourseApp.Api/Properties/launchSettings.json new file mode 100644 index 00000000..da1c7f77 --- /dev/null +++ b/CourseApp.Api/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:19002", + "sslPort": 44340 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5083", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7068;http://localhost:5083", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CourseApp.Api/Services/CourseGenerator.cs b/CourseApp.Api/Services/CourseGenerator.cs new file mode 100644 index 00000000..4b758d70 --- /dev/null +++ b/CourseApp.Api/Services/CourseGenerator.cs @@ -0,0 +1,40 @@ +using Bogus; +using CourseApp.Domain.Entity; + +namespace CourseApp.Api.Services; + +public class CourseGenerator +{ + private static readonly string[] _courseNames = + [ + "C# для начинающих", + "Python для анализа данных", + "Микросервисная архитектура", + "Docker", + "Алгоритмы и структуры данных", + "SQL и базы данных", + "Автоматизированное тестирование", + "HTML+CSS Вёрстка сайтов" + ]; + + public Course Generate(int id) + { + var faker = new Faker("ru") + .RuleFor(c => c.Id, _ => id) + .RuleFor(c => c.Name, f => f.PickRandom(_courseNames)) + .RuleFor(c => c.TeacherFullName, f => f.Name.FullName()) + //f => $"{f.Name.LastName()} {f.Name.FirstName()} {f.Name.}") + .RuleFor(c => c.StartDate, f => f.Date.SoonDateOnly(30)) + .RuleFor(c => c.EndDate, (f, c) => + c.StartDate.AddDays(f.Random.Int(30, 180))) + .RuleFor(c => c.MaxStudents, f => f.Random.Int(10, 50)) + .RuleFor(c => c.CurrentStudents, (f, c) => + f.Random.Int(0, c.MaxStudents)) + .RuleFor(c => c.HasCertificate, f => f.Random.Bool()) + .RuleFor(c => c.Price, + f => Math.Round(f.Random.Decimal(5000, 10000), 2)) + .RuleFor(c => c.Rating, f => f.Random.Int(1, 5)); + + return faker.Generate(); + } +} \ No newline at end of file diff --git a/CourseApp.Api/Services/CourseService.cs b/CourseApp.Api/Services/CourseService.cs new file mode 100644 index 00000000..4a3afea7 --- /dev/null +++ b/CourseApp.Api/Services/CourseService.cs @@ -0,0 +1,51 @@ +using System.Text.Json; +using CourseApp.Domain.Entity; +using Microsoft.Extensions.Caching.Distributed; + +namespace CourseApp.Api.Services; + +public class CourseService(IDistributedCache _cache, IConfiguration _configuration, + ILogger _logger, CourseGenerator _generator) +{ + public async Task GetCourseAsync(int id) + { + + var cacheKey = $"course-{id}"; + _logger.LogInformation("Попытка получить курс {CourseId} из кэша",id); + var cachedData = await _cache.GetStringAsync(cacheKey); + + if (!string.IsNullOrEmpty(cachedData)) + { + try + { + var cachedCourse = JsonSerializer.Deserialize(cachedData); + + if (cachedCourse != null) + { + _logger.LogInformation("Курс {CourseId} успешно получен из кэша", id); + return cachedCourse; + } + _logger.LogWarning("Курс {CourseId} найден в кэше, но десериализация вернула null", id); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка десериализации курса {CourseId} из кэша", id); + } + } + + _logger.LogInformation("Курс {CourseId} отсутствует в кэше. Начинаем генерацию", id); + + var course = _generator.Generate(id); + var expirationMinutes = _configuration.GetValue("CacheSettings:ExpirationMinutes", 5); + + var cacheOptions = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes) + }; + + await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(course), cacheOptions); + _logger.LogInformation("Курс {CourseId} сгенерирован и сохранён в кэш", id); + + return course; + } +} \ No newline at end of file diff --git a/CourseApp.Api/appsettings.Development.json b/CourseApp.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CourseApp.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CourseApp.Api/appsettings.json b/CourseApp.Api/appsettings.json new file mode 100644 index 00000000..0d4ec8d7 --- /dev/null +++ b/CourseApp.Api/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "CacheSettings": { + "ExpirationMinutes": 10 + }, + "AllowedHosts": "*" +} diff --git a/CourseApp.AppHost/AppHost.cs b/CourseApp.AppHost/AppHost.cs new file mode 100644 index 00000000..83ec3b84 --- /dev/null +++ b/CourseApp.AppHost/AppHost.cs @@ -0,0 +1,23 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis"); + +var redisCommander = builder.AddContainer( + name: "redis-commander", + image: "rediscommander/redis-commander") + .WithEnvironment("REDIS_HOSTS", "local:redis:6379") + .WithReference(redis) + .WaitFor(redis) + .WithEndpoint(port: 8081, targetPort: 8081); + +var api = builder.AddProject("courseapp-api") + .WithReference(redis) + .WaitFor(redis) + .WithExternalHttpEndpoints(); + +builder.AddProject("client") + .WithReference(api) + .WaitFor(api) + .WithExternalHttpEndpoints(); + +builder.Build().Run(); \ No newline at end of file diff --git a/CourseApp.AppHost/CourseApp.AppHost.csproj b/CourseApp.AppHost/CourseApp.AppHost.csproj new file mode 100644 index 00000000..6c4a9501 --- /dev/null +++ b/CourseApp.AppHost/CourseApp.AppHost.csproj @@ -0,0 +1,22 @@ + + + + Exe + net8.0 + enable + enable + c086dba3-3e81-4540-916e-ccad1674fa30 + + + + + + + + + + + + + + diff --git a/CourseApp.AppHost/Properties/launchSettings.json b/CourseApp.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..ebedba73 --- /dev/null +++ b/CourseApp.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:17164;http://localhost:15271", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21251", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23029", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22151" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15271", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19248", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18141", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20080" + } + } + } +} diff --git a/CourseApp.AppHost/appsettings.Development.json b/CourseApp.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CourseApp.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CourseApp.AppHost/appsettings.json b/CourseApp.AppHost/appsettings.json new file mode 100644 index 00000000..31c092aa --- /dev/null +++ b/CourseApp.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CourseApp.Domain/CourseApp.Domain.csproj b/CourseApp.Domain/CourseApp.Domain.csproj new file mode 100644 index 00000000..fa71b7ae --- /dev/null +++ b/CourseApp.Domain/CourseApp.Domain.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/CourseApp.Domain/Entity/CourseApp.cs b/CourseApp.Domain/Entity/CourseApp.cs new file mode 100644 index 00000000..4a618fdc --- /dev/null +++ b/CourseApp.Domain/Entity/CourseApp.cs @@ -0,0 +1,57 @@ +namespace CourseApp.Domain.Entity; + +/// +/// Модель учебного курса +/// +public class Course +{ + /// + /// Идентификатор курса в системе + /// + public int Id { get; set; } + + /// + /// Наименование курса + /// + public string Name { get; set; } = string.Empty; + + /// + /// ФИО преподавателя + /// + public string TeacherFullName { get; set; } = string.Empty; + + /// + /// Дата начала курса + /// + public DateOnly StartDate { get; set; } + + /// + /// Дата окончания курса + /// + public DateOnly EndDate { get; set; } + + /// + /// Максимальное количество студентов + /// + public int MaxStudents { get; set; } + + /// + /// Текущее количество записанных студентов + /// + public int CurrentStudents { get; set; } + + /// + /// Выдача сертификата + /// + public bool HasCertificate { get; set; } + + /// + /// Стоимость + /// + public decimal Price { get; set; } + + /// + /// Рейтинг + /// + public int Rating { get; set; } +} \ No newline at end of file diff --git a/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj b/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj new file mode 100644 index 00000000..7d677a24 --- /dev/null +++ b/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj @@ -0,0 +1,24 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + + + diff --git a/CourseApp.ServiceDefaults/Extensions.cs b/CourseApp.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..352a2abd --- /dev/null +++ b/CourseApp.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 OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace CourseApp.ServiceDefaults; + +/// +/// Общие настройки для сервисов Aspire: OpenTelemetry, Структурное логирование, Health checks +/// +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(options => + { + options.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; + } + + /// + /// Подключение стандартных endpoint'ов (health) + /// + 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 From 79f2a2427293a70f634f1ddc2daf36ba869aa477 Mon Sep 17 00:00:00 2001 From: daryaskhrv <113370290+daryaskhrv@users.noreply.github.com> Date: Thu, 19 Feb 2026 22:21:40 +0400 Subject: [PATCH 2/8] Update README.md --- README.md | 133 ++---------------------------------------------------- 1 file changed, 5 insertions(+), 128 deletions(-) diff --git a/README.md b/README.md index dcaa5eb7..500a4c67 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,5 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](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). - +# Сахарова Дарья 6513 +## Вариант 50 - Учебный курс +### Лабораторная работа №1 - Кэширование +Снимок экрана 2026-02-19 221447 +Снимок экрана 2026-02-19 221527 From ad3008c04e702727b32dff460a7580aa84cef09e Mon Sep 17 00:00:00 2001 From: Daryaskhrv Date: Thu, 19 Feb 2026 22:31:31 +0400 Subject: [PATCH 3/8] fix --- CourseApp.AppHost/AppHost.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/CourseApp.AppHost/AppHost.cs b/CourseApp.AppHost/AppHost.cs index 83ec3b84..99312342 100644 --- a/CourseApp.AppHost/AppHost.cs +++ b/CourseApp.AppHost/AppHost.cs @@ -12,12 +12,10 @@ var api = builder.AddProject("courseapp-api") .WithReference(redis) - .WaitFor(redis) - .WithExternalHttpEndpoints(); + .WaitFor(redis); builder.AddProject("client") .WithReference(api) - .WaitFor(api) - .WithExternalHttpEndpoints(); + .WaitFor(api); builder.Build().Run(); \ No newline at end of file From ca2d91ef53e670b35c6a9946d44de86837ffbc4d Mon Sep 17 00:00:00 2001 From: Daryaskhrv Date: Fri, 20 Feb 2026 18:15:00 +0400 Subject: [PATCH 4/8] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CourseApp.Api/Program.cs | 4 +-- CourseApp.Api/Services/CourseGenerator.cs | 40 +++++++++++++---------- CourseApp.Api/Services/CourseService.cs | 25 ++++++++++---- 3 files changed, 44 insertions(+), 25 deletions(-) diff --git a/CourseApp.Api/Program.cs b/CourseApp.Api/Program.cs index 75c1fb87..3c7c9c40 100644 --- a/CourseApp.Api/Program.cs +++ b/CourseApp.Api/Program.cs @@ -15,12 +15,12 @@ options.AddPolicy("wasm", policy => { policy.AllowAnyOrigin() - .WithMethods("GET", "POST") + .WithMethods("GET") .WithHeaders("Content-Type"); }); }); -builder.Services.AddScoped(); +builder.Services.AddSingleton(); builder.Services.AddScoped(); var app = builder.Build(); diff --git a/CourseApp.Api/Services/CourseGenerator.cs b/CourseApp.Api/Services/CourseGenerator.cs index 4b758d70..54439ae2 100644 --- a/CourseApp.Api/Services/CourseGenerator.cs +++ b/CourseApp.Api/Services/CourseGenerator.cs @@ -3,6 +3,9 @@ namespace CourseApp.Api.Services; +/// +/// Генератор тестовых данных при отсутствии данных в кэше +/// public class CourseGenerator { private static readonly string[] _courseNames = @@ -17,24 +20,27 @@ public class CourseGenerator "HTML+CSS Вёрстка сайтов" ]; + /// + /// Преднастроенный генератор + /// + private static readonly Faker _faker = new Faker("ru") + .RuleFor(c => c.Name, f => f.PickRandom(_courseNames)) + .RuleFor(c => c.TeacherFullName, f => f.Name.FullName()) + .RuleFor(c => c.StartDate, f => f.Date.SoonDateOnly(30)) + .RuleFor(c => c.EndDate, (f, c) => c.StartDate.AddDays(f.Random.Int(30, 180))) + .RuleFor(c => c.MaxStudents, f => f.Random.Int(10, 50)) + .RuleFor(c => c.CurrentStudents, (f, c) => f.Random.Int(0, c.MaxStudents)) + .RuleFor(c => c.HasCertificate, f => f.Random.Bool()) + .RuleFor(c => c.Price, f => Math.Round(f.Random.Decimal(5000, 10000), 2)) + .RuleFor(c => c.Rating, f => f.Random.Int(1, 5)); + + /// + /// Генерирует новый экземпляр курса с указанным идентификатором + /// public Course Generate(int id) { - var faker = new Faker("ru") - .RuleFor(c => c.Id, _ => id) - .RuleFor(c => c.Name, f => f.PickRandom(_courseNames)) - .RuleFor(c => c.TeacherFullName, f => f.Name.FullName()) - //f => $"{f.Name.LastName()} {f.Name.FirstName()} {f.Name.}") - .RuleFor(c => c.StartDate, f => f.Date.SoonDateOnly(30)) - .RuleFor(c => c.EndDate, (f, c) => - c.StartDate.AddDays(f.Random.Int(30, 180))) - .RuleFor(c => c.MaxStudents, f => f.Random.Int(10, 50)) - .RuleFor(c => c.CurrentStudents, (f, c) => - f.Random.Int(0, c.MaxStudents)) - .RuleFor(c => c.HasCertificate, f => f.Random.Bool()) - .RuleFor(c => c.Price, - f => Math.Round(f.Random.Decimal(5000, 10000), 2)) - .RuleFor(c => c.Rating, f => f.Random.Int(1, 5)); - - return faker.Generate(); + var course = _faker.Generate(); + course.Id = id; + return course; } } \ No newline at end of file diff --git a/CourseApp.Api/Services/CourseService.cs b/CourseApp.Api/Services/CourseService.cs index 4a3afea7..357ea8eb 100644 --- a/CourseApp.Api/Services/CourseService.cs +++ b/CourseApp.Api/Services/CourseService.cs @@ -4,9 +4,15 @@ namespace CourseApp.Api.Services; +/// +/// Сервис для получения информации о курсе +/// public class CourseService(IDistributedCache _cache, IConfiguration _configuration, ILogger _logger, CourseGenerator _generator) { + /// + /// Получает курс по идентификатору из кэша или с помощью генератора + /// public async Task GetCourseAsync(int id) { @@ -36,16 +42,23 @@ public async Task GetCourseAsync(int id) _logger.LogInformation("Курс {CourseId} отсутствует в кэше. Начинаем генерацию", id); var course = _generator.Generate(id); - var expirationMinutes = _configuration.GetValue("CacheSettings:ExpirationMinutes", 5); - var cacheOptions = new DistributedCacheEntryOptions + try { - AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes) - }; + var expirationMinutes = _configuration.GetValue("CacheSettings:ExpirationMinutes", 5); - await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(course), cacheOptions); - _logger.LogInformation("Курс {CourseId} сгенерирован и сохранён в кэш", id); + var cacheOptions = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes) + }; + await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(course), cacheOptions); + _logger.LogInformation("Курс {CourseId} сгенерирован и сохранён в кэш", id); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Не удалось сохранить курс {CourseId} в кэш. Работа продолжается без кэширования.", id); + } return course; } } \ No newline at end of file From 4ac591b6081c5fc61e7378f6cccdd16918b68c41 Mon Sep 17 00:00:00 2001 From: Daryaskhrv Date: Thu, 2 Apr 2026 19:39:20 +0400 Subject: [PATCH 5/8] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Api.Gateway/Api.Gateway.csproj | 17 +++++++ Api.Gateway/LoadBalancers/WeightedRandom.cs | 51 +++++++++++++++++++++ Api.Gateway/Program.cs | 33 +++++++++++++ Api.Gateway/Properties/launchSettings.json | 38 +++++++++++++++ Api.Gateway/appsettings.Development.json | 8 ++++ Api.Gateway/appsettings.json | 12 +++++ Api.Gateway/ocelot.json | 38 +++++++++++++++ Client.Wasm/Components/StudentCard.razor | 2 +- Client.Wasm/Properties/launchSettings.json | 6 +-- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.sln | 8 +++- CourseApp.Api/Program.cs | 11 ----- CourseApp.AppHost/AppHost.cs | 18 +++++--- CourseApp.AppHost/CourseApp.AppHost.csproj | 1 + 14 files changed, 222 insertions(+), 23 deletions(-) create mode 100644 Api.Gateway/Api.Gateway.csproj create mode 100644 Api.Gateway/LoadBalancers/WeightedRandom.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..522372bf --- /dev/null +++ b/Api.Gateway/Api.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/Api.Gateway/LoadBalancers/WeightedRandom.cs b/Api.Gateway/LoadBalancers/WeightedRandom.cs new file mode 100644 index 00000000..e57f25f8 --- /dev/null +++ b/Api.Gateway/LoadBalancers/WeightedRandom.cs @@ -0,0 +1,51 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace Api.Gateway.LoadBalancers; + +/// +/// Балансировщик нагрузки, выбирающий downstream-сервис случайным образом с учётом весов. +/// Чем больше вес у сервиса, тем выше вероятность его выбора. +/// Веса задаются в конфигурации (WeightedRandom:Weights) и применяются к сервисам в порядке их перечисления в маршруте Ocelot. +/// +/// Фабричная функция получения списка downstream-сервисов. +/// Конфигурация приложения с секцией весов. +public class WeightedRandom(Func>> services, IConfiguration configuration) : ILoadBalancer +{ + private static readonly object _locker = new(); + private readonly int[] _weights = configuration + .GetSection("WeightedRandom:Weights") + .Get() ?? [1, 1, 1, 1, 1]; + private readonly Random _random = new(111); + + public string Type => nameof(WeightedRandom); + + public async Task> LeaseAsync(HttpContext httpContext) + { + var serviceList = await services(); + + if (serviceList.Count == 0) + throw new InvalidOperationException("Нет доступных сервисов"); + + lock (_locker) + { + var totalWeight = 0; + for (var i = 0; i < serviceList.Count; i++) + totalWeight += i < _weights.Length ? _weights[i] : 1; + + var threshold = _random.Next(totalWeight); + var cumulative = 0; + for (var i = 0; i < serviceList.Count; i++) + { + cumulative += i < _weights.Length ? _weights[i] : 1; + if (threshold < cumulative) + return new OkResponse(serviceList[i].HostAndPort); + } + + return new OkResponse(serviceList[^1].HostAndPort); + } + } + + public void Release(ServiceHostAndPort hostAndPort) { } +} diff --git a/Api.Gateway/Program.cs b/Api.Gateway/Program.cs new file mode 100644 index 00000000..156c46c9 --- /dev/null +++ b/Api.Gateway/Program.cs @@ -0,0 +1,33 @@ +using Api.Gateway.LoadBalancers; +using CourseApp.ServiceDefaults; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.Services.AddServiceDiscovery(); +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); +builder.Services.AddOcelot() + .AddCustomLoadBalancer((sp, _, provider) => + new WeightedRandom(provider.GetAsync, sp.GetRequiredService())); + +builder.Services.AddCors(options => +{ + options.AddPolicy("wasm", policy => + { + policy.AllowAnyOrigin() + .WithMethods("GET") + .WithHeaders("Content-Type"); + }); +}); + +var app = builder.Build(); + +app.UseCors("wasm"); + +app.MapDefaultEndpoints(); + +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..c94313c8 --- /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:46205", + "sslPort": 44343 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5200", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7186;http://localhost:5200", + "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..45d3fe4d --- /dev/null +++ b/Api.Gateway/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "WeightedRandom": { + "Weights": [ 5, 4, 3, 2, 1 ] + } +} diff --git a/Api.Gateway/ocelot.json b/Api.Gateway/ocelot.json new file mode 100644 index 00000000..4b90a21e --- /dev/null +++ b/Api.Gateway/ocelot.json @@ -0,0 +1,38 @@ +{ + "Routes": [ + { + "UpstreamPathTemplate": "/course", + "UpstreamHttpMethod": [ "GET" ], + "DownstreamPathTemplate": "/api/course", + "DownstreamScheme": "https", + "LoadBalancerOptions": { + "Type": "WeightedRandom" + }, + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 8000 + }, + { + "Host": "localhost", + "Port": 8001 + }, + { + "Host": "localhost", + "Port": 8002 + }, + { + "Host": "localhost", + "Port": 8003 + }, + { + "Host": "localhost", + "Port": 8004 + } + ] + } + ], + "GlobalConfiguration": { + "BaseUrl": "https://localhost:7186" + } +} diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 8acfba9d..b281cc98 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,7 +4,7 @@ - Номер №1 Кэширование + Номер №2 Балансировка нагрузки Вариант №50 "Учебный курс" Выполнена Сахаровой Дарьей 6513 Ссылка на форк 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 3e8284f6..e8ac606e 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "https://localhost:7068/api/course" + "BaseAddress": "https://localhost:7186/course" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index c0634a98..f8762c78 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 18 -VisualStudioVersion = 18.3.11505.172 d18.3 +VisualStudioVersion = 18.3.11505.172 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}" EndProject @@ -13,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.ServiceDefaults", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.AppHost", "CourseApp.AppHost\CourseApp.AppHost.csproj", "{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -39,6 +41,10 @@ Global {8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Debug|Any CPU.Build.0 = Debug|Any CPU {8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Release|Any CPU.ActiveCfg = Release|Any CPU {8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Release|Any CPU.Build.0 = Release|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CourseApp.Api/Program.cs b/CourseApp.Api/Program.cs index 3c7c9c40..69a8a862 100644 --- a/CourseApp.Api/Program.cs +++ b/CourseApp.Api/Program.cs @@ -10,16 +10,6 @@ builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); -builder.Services.AddCors(options => -{ - options.AddPolicy("wasm", policy => - { - policy.AllowAnyOrigin() - .WithMethods("GET") - .WithHeaders("Content-Type"); - }); -}); - builder.Services.AddSingleton(); builder.Services.AddScoped(); @@ -33,7 +23,6 @@ app.MapDefaultEndpoints(); app.UseHttpsRedirection(); -app.UseCors("wasm"); app.UseAuthorization(); app.MapControllers(); app.Run(); \ No newline at end of file diff --git a/CourseApp.AppHost/AppHost.cs b/CourseApp.AppHost/AppHost.cs index 99312342..e838d96b 100644 --- a/CourseApp.AppHost/AppHost.cs +++ b/CourseApp.AppHost/AppHost.cs @@ -2,7 +2,7 @@ var redis = builder.AddRedis("redis"); -var redisCommander = builder.AddContainer( +builder.AddContainer( name: "redis-commander", image: "rediscommander/redis-commander") .WithEnvironment("REDIS_HOSTS", "local:redis:6379") @@ -10,12 +10,18 @@ .WaitFor(redis) .WithEndpoint(port: 8081, targetPort: 8081); -var api = builder.AddProject("courseapp-api") - .WithReference(redis) - .WaitFor(redis); +var gateway = builder.AddProject("api-gateway"); + +for (var i = 0; i < 5; i++) +{ + var api = builder.AddProject($"courseapp-api-{i}", launchProfileName: null) + .WithReference(redis) + .WaitFor(redis) + .WithHttpsEndpoint(port: 8000 + i); + gateway.WaitFor(api); +} builder.AddProject("client") - .WithReference(api) - .WaitFor(api); + .WaitFor(gateway); builder.Build().Run(); \ No newline at end of file diff --git a/CourseApp.AppHost/CourseApp.AppHost.csproj b/CourseApp.AppHost/CourseApp.AppHost.csproj index 6c4a9501..3a23b25b 100644 --- a/CourseApp.AppHost/CourseApp.AppHost.csproj +++ b/CourseApp.AppHost/CourseApp.AppHost.csproj @@ -14,6 +14,7 @@ + From 666f2479128d2989a48f9126debb6c732f1c6ea5 Mon Sep 17 00:00:00 2001 From: Daryaskhrv Date: Sun, 5 Apr 2026 11:32:56 +0400 Subject: [PATCH 6/8] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BC=D0=B5=D0=BB=D0=BE=D1=87=D0=B5?= =?UTF-8?q?=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Api.Gateway/LoadBalancers/WeightedRandom.cs | 31 +++++++++------------ CourseApp.AppHost/AppHost.cs | 11 ++------ 2 files changed, 15 insertions(+), 27 deletions(-) diff --git a/Api.Gateway/LoadBalancers/WeightedRandom.cs b/Api.Gateway/LoadBalancers/WeightedRandom.cs index e57f25f8..0f495f89 100644 --- a/Api.Gateway/LoadBalancers/WeightedRandom.cs +++ b/Api.Gateway/LoadBalancers/WeightedRandom.cs @@ -13,11 +13,9 @@ namespace Api.Gateway.LoadBalancers; /// Конфигурация приложения с секцией весов. public class WeightedRandom(Func>> services, IConfiguration configuration) : ILoadBalancer { - private static readonly object _locker = new(); private readonly int[] _weights = configuration .GetSection("WeightedRandom:Weights") .Get() ?? [1, 1, 1, 1, 1]; - private readonly Random _random = new(111); public string Type => nameof(WeightedRandom); @@ -28,24 +26,21 @@ public async Task> LeaseAsync(HttpContext httpConte if (serviceList.Count == 0) throw new InvalidOperationException("Нет доступных сервисов"); - lock (_locker) + var totalWeight = 0; + for (var i = 0; i < serviceList.Count; i++) + totalWeight += i < _weights.Length ? _weights[i] : 1; + + var threshold = Random.Shared.Next(totalWeight); + var cumulative = 0; + for (var i = 0; i < serviceList.Count; i++) { - var totalWeight = 0; - for (var i = 0; i < serviceList.Count; i++) - totalWeight += i < _weights.Length ? _weights[i] : 1; - - var threshold = _random.Next(totalWeight); - var cumulative = 0; - for (var i = 0; i < serviceList.Count; i++) - { - cumulative += i < _weights.Length ? _weights[i] : 1; - if (threshold < cumulative) - return new OkResponse(serviceList[i].HostAndPort); - } - - return new OkResponse(serviceList[^1].HostAndPort); + cumulative += i < _weights.Length ? _weights[i] : 1; + if (threshold < cumulative) + return new OkResponse(serviceList[i].HostAndPort); } + + return new OkResponse(serviceList[^1].HostAndPort); } public void Release(ServiceHostAndPort hostAndPort) { } -} +} \ No newline at end of file diff --git a/CourseApp.AppHost/AppHost.cs b/CourseApp.AppHost/AppHost.cs index e838d96b..4150f679 100644 --- a/CourseApp.AppHost/AppHost.cs +++ b/CourseApp.AppHost/AppHost.cs @@ -1,14 +1,7 @@ var builder = DistributedApplication.CreateBuilder(args); -var redis = builder.AddRedis("redis"); - -builder.AddContainer( - name: "redis-commander", - image: "rediscommander/redis-commander") - .WithEnvironment("REDIS_HOSTS", "local:redis:6379") - .WithReference(redis) - .WaitFor(redis) - .WithEndpoint(port: 8081, targetPort: 8081); +var redis = builder.AddRedis("redis") + .WithRedisCommander(); var gateway = builder.AddProject("api-gateway"); From 964875297e4ea3725e32b2e3c240ade756538646 Mon Sep 17 00:00:00 2001 From: Daryaskhrv Date: Thu, 23 Apr 2026 17:18:51 +0400 Subject: [PATCH 7/8] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Api.Gateway/Api.Gateway.csproj | 2 +- Client.Wasm/Components/StudentCard.razor | 2 +- CloudDevelopment.sln | 12 ++ CourseApp.Api/CourseApp.Api.csproj | 31 ++-- CourseApp.Api/Messaging/IProducerService.cs | 15 ++ CourseApp.Api/Messaging/SqsProducerService.cs | 41 +++++ CourseApp.Api/Program.cs | 9 +- CourseApp.Api/Services/CourseService.cs | 8 +- CourseApp.AppHost/AppHost.cs | 34 +++- .../CloudFormation/course-template.yaml | 32 ++++ CourseApp.AppHost/CourseApp.AppHost.csproj | 36 ++-- CourseApp.AppHost/appsettings.json | 3 + CourseApp.Domain/Entity/CourseApp.cs | 5 +- .../CourseApp.ServiceDefaults.csproj | 37 ++-- .../Controllers/FileStorageController.cs | 63 +++++++ .../Messaging/SqsConsumerService.cs | 69 +++++++ Service.FileStorage/Program.cs | 30 +++ .../Properties/launchSettings.json | 38 ++++ .../Service.FileStorage.csproj | 23 +++ .../Storage/IFileStorageService.cs | 33 ++++ .../Storage/MinioFileStorageService.cs | 128 +++++++++++++ .../appsettings.Development.json | 8 + Service.FileStorage/appsettings.json | 9 + .../IntegrationTest.cs" | 174 ++++++++++++++++++ .../\320\241ourseApp.AppHost.Test.csproj" | 33 ++++ 25 files changed, 825 insertions(+), 50 deletions(-) create mode 100644 CourseApp.Api/Messaging/IProducerService.cs create mode 100644 CourseApp.Api/Messaging/SqsProducerService.cs create mode 100644 CourseApp.AppHost/CloudFormation/course-template.yaml create mode 100644 Service.FileStorage/Controllers/FileStorageController.cs create mode 100644 Service.FileStorage/Messaging/SqsConsumerService.cs create mode 100644 Service.FileStorage/Program.cs create mode 100644 Service.FileStorage/Properties/launchSettings.json create mode 100644 Service.FileStorage/Service.FileStorage.csproj create mode 100644 Service.FileStorage/Storage/IFileStorageService.cs create mode 100644 Service.FileStorage/Storage/MinioFileStorageService.cs create mode 100644 Service.FileStorage/appsettings.Development.json create mode 100644 Service.FileStorage/appsettings.json create mode 100644 "\320\241ourseApp.AppHost.Test/IntegrationTest.cs" create mode 100644 "\320\241ourseApp.AppHost.Test/\320\241ourseApp.AppHost.Test.csproj" diff --git a/Api.Gateway/Api.Gateway.csproj b/Api.Gateway/Api.Gateway.csproj index 522372bf..77ce9775 100644 --- a/Api.Gateway/Api.Gateway.csproj +++ b/Api.Gateway/Api.Gateway.csproj @@ -14,4 +14,4 @@ - + \ No newline at end of file diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index b281cc98..70343b3d 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,7 +4,7 @@ - Номер №2 Балансировка нагрузки + Номер №3 Интеграционное тестирование Вариант №50 "Учебный курс" Выполнена Сахаровой Дарьей 6513 Ссылка на форк diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index f8762c78..3dabb63e 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -15,6 +15,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.AppHost", "Course EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Service.FileStorage", "Service.FileStorage\Service.FileStorage.csproj", "{395BE70D-7DB4-7F62-3FF9-C8EE68E5C610}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "СourseApp.AppHost.Test", "СourseApp.AppHost.Test\СourseApp.AppHost.Test.csproj", "{EEC7C7EE-19AF-4315-8053-18EB603B0C73}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -45,6 +49,14 @@ Global {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.Build.0 = Debug|Any CPU {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.ActiveCfg = Release|Any CPU {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.Build.0 = Release|Any CPU + {395BE70D-7DB4-7F62-3FF9-C8EE68E5C610}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {395BE70D-7DB4-7F62-3FF9-C8EE68E5C610}.Debug|Any CPU.Build.0 = Debug|Any CPU + {395BE70D-7DB4-7F62-3FF9-C8EE68E5C610}.Release|Any CPU.ActiveCfg = Release|Any CPU + {395BE70D-7DB4-7F62-3FF9-C8EE68E5C610}.Release|Any CPU.Build.0 = Release|Any CPU + {EEC7C7EE-19AF-4315-8053-18EB603B0C73}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EEC7C7EE-19AF-4315-8053-18EB603B0C73}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EEC7C7EE-19AF-4315-8053-18EB603B0C73}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EEC7C7EE-19AF-4315-8053-18EB603B0C73}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CourseApp.Api/CourseApp.Api.csproj b/CourseApp.Api/CourseApp.Api.csproj index 4fec257e..c24a76ad 100644 --- a/CourseApp.Api/CourseApp.Api.csproj +++ b/CourseApp.Api/CourseApp.Api.csproj @@ -1,20 +1,23 @@ - - net8.0 - enable - enable - + + net8.0 + enable + enable + - - - - - + + + + + + + + - - - - + + + + diff --git a/CourseApp.Api/Messaging/IProducerService.cs b/CourseApp.Api/Messaging/IProducerService.cs new file mode 100644 index 00000000..88a3e093 --- /dev/null +++ b/CourseApp.Api/Messaging/IProducerService.cs @@ -0,0 +1,15 @@ +using CourseApp.Domain.Entity; + +namespace CourseApp.Api.Messaging; + +/// +/// Интерфейс службы для отправки сгенерированных курсов в брокер сообщений +/// +public interface IProducerService +{ + /// + /// Отправляет сообщение в брокер + /// + /// Учебный курс + public Task SendMessage(Course course); +} diff --git a/CourseApp.Api/Messaging/SqsProducerService.cs b/CourseApp.Api/Messaging/SqsProducerService.cs new file mode 100644 index 00000000..44a3118c --- /dev/null +++ b/CourseApp.Api/Messaging/SqsProducerService.cs @@ -0,0 +1,41 @@ +using System.Net; +using System.Text.Json; +using Amazon.SQS; +using CourseApp.Domain.Entity; + +namespace CourseApp.Api.Messaging; + +/// +/// Служба для отправки сообщений в SQS +/// +/// Клиент SQS +/// Конфигурация +/// Логгер +public class SqsProducerService(IAmazonSQS client, IConfiguration configuration, ILogger logger) : IProducerService +{ + private static readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + private readonly string _queueName = configuration["AWS:Resources:SQSQueueName"] + ?? throw new KeyNotFoundException("SQS queue name was not found in configuration"); + + /// + public async Task SendMessage(Course course) + { + try + { + var json = JsonSerializer.Serialize(course, _jsonOptions); + var response = await client.SendMessageAsync(_queueName, json); + if (response.HttpStatusCode == HttpStatusCode.OK) + logger.LogInformation("Курс {id} отправлен в файловый сервис через SQS", course.Id); + else + throw new Exception($"SQS вернул статус {response.HttpStatusCode}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Не удалось отправить курс в очередь SQS"); + } + } +} diff --git a/CourseApp.Api/Program.cs b/CourseApp.Api/Program.cs index 69a8a862..746bc78c 100644 --- a/CourseApp.Api/Program.cs +++ b/CourseApp.Api/Program.cs @@ -1,5 +1,8 @@ +using Amazon.SQS; +using CourseApp.Api.Messaging; using CourseApp.Api.Services; using CourseApp.ServiceDefaults; +using LocalStack.Client.Extensions; var builder = WebApplication.CreateBuilder(args); @@ -13,6 +16,10 @@ builder.Services.AddSingleton(); builder.Services.AddScoped(); +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddScoped(); + var app = builder.Build(); if (app.Environment.IsDevelopment()) @@ -25,4 +32,4 @@ app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); -app.Run(); \ No newline at end of file +app.Run(); diff --git a/CourseApp.Api/Services/CourseService.cs b/CourseApp.Api/Services/CourseService.cs index 357ea8eb..60024f46 100644 --- a/CourseApp.Api/Services/CourseService.cs +++ b/CourseApp.Api/Services/CourseService.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using CourseApp.Api.Messaging; using CourseApp.Domain.Entity; using Microsoft.Extensions.Caching.Distributed; @@ -8,7 +9,8 @@ namespace CourseApp.Api.Services; /// Сервис для получения информации о курсе /// public class CourseService(IDistributedCache _cache, IConfiguration _configuration, - ILogger _logger, CourseGenerator _generator) + ILogger _logger, CourseGenerator _generator, + IProducerService _producer) { /// /// Получает курс по идентификатору из кэша или с помощью генератора @@ -17,7 +19,7 @@ public async Task GetCourseAsync(int id) { var cacheKey = $"course-{id}"; - _logger.LogInformation("Попытка получить курс {CourseId} из кэша",id); + _logger.LogInformation("Попытка получить курс {CourseId} из кэша", id); var cachedData = await _cache.GetStringAsync(cacheKey); if (!string.IsNullOrEmpty(cachedData)) @@ -43,6 +45,8 @@ public async Task GetCourseAsync(int id) var course = _generator.Generate(id); + await _producer.SendMessage(course); + try { var expirationMinutes = _configuration.GetValue("CacheSettings:ExpirationMinutes", 5); diff --git a/CourseApp.AppHost/AppHost.cs b/CourseApp.AppHost/AppHost.cs index 4150f679..6ae5266d 100644 --- a/CourseApp.AppHost/AppHost.cs +++ b/CourseApp.AppHost/AppHost.cs @@ -1,3 +1,6 @@ +using Amazon; +using Aspire.Hosting.LocalStack.Container; + var builder = DistributedApplication.CreateBuilder(args); var redis = builder.AddRedis("redis") @@ -5,11 +8,31 @@ var gateway = builder.AddProject("api-gateway"); +var awsConfig = builder.AddAWSSDKConfig() + .WithProfile("default") + .WithRegion(RegionEndpoint.EUCentral1); + +var localstack = builder.AddLocalStack("courseapp-localstack", awsConfig: awsConfig, configureContainer: container => +{ + container.Lifetime = ContainerLifetime.Session; + container.DebugLevel = 1; + container.LogLevel = LocalStackLogLevel.Debug; + container.Port = 4566; + container.AdditionalEnvironmentVariables.Add("DEBUG", "1"); +}); + +var awsResources = builder.AddAWSCloudFormationTemplate("resources", "CloudFormation/course-template.yaml", "courseapp") + .WithReference(awsConfig); + +var minio = builder.AddMinioContainer("courseapp-minio"); + for (var i = 0; i < 5; i++) { var api = builder.AddProject($"courseapp-api-{i}", launchProfileName: null) .WithReference(redis) + .WithReference(awsResources) .WaitFor(redis) + .WaitFor(awsResources) .WithHttpsEndpoint(port: 8000 + i); gateway.WaitFor(api); } @@ -17,4 +40,13 @@ builder.AddProject("client") .WaitFor(gateway); -builder.Build().Run(); \ No newline at end of file +builder.AddProject("service-filestorage") + .WithReference(awsResources) + .WithReference(minio) + .WithEnvironment("AWS__Resources__MinioBucketName", "courseapp-bucket") + .WaitFor(awsResources) + .WaitFor(minio); + +builder.UseLocalStack(localstack); + +builder.Build().Run(); diff --git a/CourseApp.AppHost/CloudFormation/course-template.yaml b/CourseApp.AppHost/CloudFormation/course-template.yaml new file mode 100644 index 00000000..32c378f8 --- /dev/null +++ b/CourseApp.AppHost/CloudFormation/course-template.yaml @@ -0,0 +1,32 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: 'Cloud formation template for course app project' + +Parameters: + QueueName: + Type: String + Description: Name for the SQS queue + Default: 'course-queue' + +Resources: + CourseQueue: + Type: AWS::SQS::Queue + Properties: + QueueName: !Ref QueueName + VisibilityTimeout: 30 + MessageRetentionPeriod: 345600 + DelaySeconds: 0 + ReceiveMessageWaitTimeSeconds: 0 + Tags: + - Key: Name + Value: !Ref QueueName + - Key: Environment + Value: Sample + +Outputs: + SQSQueueName: + Description: Name of the SQS queue + Value: !GetAtt CourseQueue.QueueName + + SQSQueueArn: + Description: ARN of the SQS queue + Value: !GetAtt CourseQueue.Arn diff --git a/CourseApp.AppHost/CourseApp.AppHost.csproj b/CourseApp.AppHost/CourseApp.AppHost.csproj index 3a23b25b..30d0403a 100644 --- a/CourseApp.AppHost/CourseApp.AppHost.csproj +++ b/CourseApp.AppHost/CourseApp.AppHost.csproj @@ -1,23 +1,37 @@ - + - - Exe - net8.0 - enable - enable - c086dba3-3e81-4540-916e-ccad1674fa30 - + + + + Exe + net8.0 + enable + enable + c086dba3-3e81-4540-916e-ccad1674fa30 + - - + + + + + + + + + + Always + + + + + - diff --git a/CourseApp.AppHost/appsettings.json b/CourseApp.AppHost/appsettings.json index 31c092aa..a6b256bb 100644 --- a/CourseApp.AppHost/appsettings.json +++ b/CourseApp.AppHost/appsettings.json @@ -5,5 +5,8 @@ "Microsoft.AspNetCore": "Warning", "Aspire.Hosting.Dcp": "Warning" } + }, + "LocalStack": { + "UseLocalStack": true } } diff --git a/CourseApp.Domain/Entity/CourseApp.cs b/CourseApp.Domain/Entity/CourseApp.cs index 4a618fdc..29530a72 100644 --- a/CourseApp.Domain/Entity/CourseApp.cs +++ b/CourseApp.Domain/Entity/CourseApp.cs @@ -1,4 +1,6 @@ -namespace CourseApp.Domain.Entity; +using System.Text.Json.Serialization; + +namespace CourseApp.Domain.Entity; /// /// Модель учебного курса @@ -8,6 +10,7 @@ public class Course /// /// Идентификатор курса в системе /// + [JsonPropertyName("id")] public int Id { get; set; } /// diff --git a/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj b/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj index 7d677a24..f1484c37 100644 --- a/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj +++ b/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj @@ -1,24 +1,25 @@  - - net8.0 - enable - enable - true - + + net8.0 + enable + enable + true + - - - + + + - - - - - - - - - + + + + + + + + + + diff --git a/Service.FileStorage/Controllers/FileStorageController.cs b/Service.FileStorage/Controllers/FileStorageController.cs new file mode 100644 index 00000000..dedbf63f --- /dev/null +++ b/Service.FileStorage/Controllers/FileStorageController.cs @@ -0,0 +1,63 @@ +using System.Text; +using System.Text.Json.Nodes; +using Microsoft.AspNetCore.Mvc; +using Service.FileStorage.Storage; + +namespace Service.FileStorage.Controllers; + +/// +/// Контроллер для взаимодействия с объектным хранилищем +/// +/// Служба для работы с хранилищем +/// Логгер +[ApiController] +[Route("api/files")] +public class FileStorageController(IFileStorageService storageService, ILogger logger) : ControllerBase +{ + /// + /// Получает список хранящихся в бакете файлов + /// + /// Список ключей файлов + [HttpGet] + [ProducesResponseType(200)] + [ProducesResponseType(500)] + public async Task>> ListFiles() + { + logger.LogInformation("Вызван метод {method} контроллера {controller}", nameof(ListFiles), nameof(FileStorageController)); + try + { + var list = await storageService.GetFileList(); + logger.LogInformation("Получен список из {count} файлов из бакета", list.Count); + return Ok(list); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при выполнении метода {method} контроллера {controller}", nameof(ListFiles), nameof(FileStorageController)); + return BadRequest(ex.Message); + } + } + + /// + /// Получает JSON-представление хранящегося в бакете файла + /// + /// Ключ файла + /// JSON-представление файла + [HttpGet("{key}")] + [ProducesResponseType(200)] + [ProducesResponseType(500)] + public async Task> GetFile(string key) + { + logger.LogInformation("Вызван метод {method} контроллера {controller}", nameof(GetFile), nameof(FileStorageController)); + try + { + var node = await storageService.DownloadFile(key); + logger.LogInformation("Получен JSON размером {size} байт", Encoding.UTF8.GetByteCount(node.ToJsonString())); + return Ok(node); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при выполнении метода {method} контроллера {controller}", nameof(GetFile), nameof(FileStorageController)); + return BadRequest(ex.Message); + } + } +} diff --git a/Service.FileStorage/Messaging/SqsConsumerService.cs b/Service.FileStorage/Messaging/SqsConsumerService.cs new file mode 100644 index 00000000..d9227ec2 --- /dev/null +++ b/Service.FileStorage/Messaging/SqsConsumerService.cs @@ -0,0 +1,69 @@ +using Amazon.SQS; +using Amazon.SQS.Model; +using Service.FileStorage.Storage; + +namespace Service.FileStorage.Messaging; + +/// +/// Клиентская служба для приема сообщений из очереди SQS +/// +/// Клиент SQS +/// Фабрика контекста +/// Конфигурация +/// Логгер +public class SqsConsumerService(IAmazonSQS sqsClient, + IServiceScopeFactory scopeFactory, + IConfiguration configuration, + ILogger logger) : BackgroundService +{ + private readonly string _queueName = configuration["AWS:Resources:SQSQueueName"] + ?? throw new KeyNotFoundException("SQS queue name was not found in configuration"); + + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + logger.LogInformation("Служба потребителя SQS запущена"); + + while (!stoppingToken.IsCancellationRequested) + { + var response = await sqsClient.ReceiveMessageAsync( + new ReceiveMessageRequest + { + QueueUrl = _queueName, + MaxNumberOfMessages = 10, + WaitTimeSeconds = 5 + }, stoppingToken); + + if (response == null) + { + logger.LogWarning("Получен пустой ответ из очереди {queue}", _queueName); + continue; + } + + logger.LogInformation("Получено {count} сообщений из очереди", response.Messages?.Count ?? 0); + + if (response.Messages != null) + { + foreach (var message in response.Messages) + { + try + { + logger.LogInformation("Обработка сообщения {messageId}", message.MessageId); + + using var scope = scopeFactory.CreateScope(); + var storageService = scope.ServiceProvider.GetRequiredService(); + await storageService.UploadFile(message.Body); + + await sqsClient.DeleteMessageAsync(_queueName, message.ReceiptHandle, stoppingToken); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при обработке сообщения {messageId}", message.MessageId); + continue; + } + } + logger.LogInformation("Пачка из {count} сообщений обработана", response.Messages.Count); + } + } + } +} diff --git a/Service.FileStorage/Program.cs b/Service.FileStorage/Program.cs new file mode 100644 index 00000000..f62c3811 --- /dev/null +++ b/Service.FileStorage/Program.cs @@ -0,0 +1,30 @@ +using Amazon.SQS; +using CourseApp.ServiceDefaults; +using LocalStack.Client.Extensions; +using Service.FileStorage.Messaging; +using Service.FileStorage.Storage; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Services.AddControllers(); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddHostedService(); + +builder.AddMinioClient("courseapp-minio"); +builder.Services.AddScoped(); + +var app = builder.Build(); + +using (var scope = app.Services.CreateScope()) +{ + var storage = scope.ServiceProvider.GetRequiredService(); + await storage.EnsureBucketExists(); +} + +app.MapDefaultEndpoints(); +app.MapControllers(); +app.Run(); diff --git a/Service.FileStorage/Properties/launchSettings.json b/Service.FileStorage/Properties/launchSettings.json new file mode 100644 index 00000000..43b795e7 --- /dev/null +++ b/Service.FileStorage/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:42783", + "sslPort": 44397 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5250", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7208;http://localhost:5250", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Service.FileStorage/Service.FileStorage.csproj b/Service.FileStorage/Service.FileStorage.csproj new file mode 100644 index 00000000..fcaaa268 --- /dev/null +++ b/Service.FileStorage/Service.FileStorage.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + true + $(NoWarn);1591 + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Service.FileStorage/Storage/IFileStorageService.cs b/Service.FileStorage/Storage/IFileStorageService.cs new file mode 100644 index 00000000..d9131053 --- /dev/null +++ b/Service.FileStorage/Storage/IFileStorageService.cs @@ -0,0 +1,33 @@ +using System.Text.Json.Nodes; + +namespace Service.FileStorage.Storage; + +/// +/// Интерфейс службы для манипуляции файлами в объектном хранилище +/// +public interface IFileStorageService +{ + /// + /// Отправляет файл в хранилище + /// + /// Строковая репрезентация сохраняемого файла + public Task UploadFile(string fileData); + + /// + /// Получает список всех файлов из хранилища + /// + /// Список ключей файлов + public Task> GetFileList(); + + /// + /// Получает строковую репрезентацию файла из хранилища + /// + /// Ключ файла в бакете + /// JSON-репрезентация прочтенного файла + public Task DownloadFile(string key); + + /// + /// Создает бакет при необходимости + /// + public Task EnsureBucketExists(); +} diff --git a/Service.FileStorage/Storage/MinioFileStorageService.cs b/Service.FileStorage/Storage/MinioFileStorageService.cs new file mode 100644 index 00000000..36bcedc8 --- /dev/null +++ b/Service.FileStorage/Storage/MinioFileStorageService.cs @@ -0,0 +1,128 @@ +using System.Net; +using System.Text; +using System.Text.Json.Nodes; +using Minio; +using Minio.DataModel.Args; + +namespace Service.FileStorage.Storage; + +/// +/// Служба для манипуляции файлами в объектном хранилище MinIO +/// +/// MinIO клиент +/// Конфигурация +/// Логгер +public class MinioFileStorageService(IMinioClient client, IConfiguration configuration, ILogger logger) : IFileStorageService +{ + private readonly string _bucketName = configuration["AWS:Resources:MinioBucketName"] + ?? throw new KeyNotFoundException("Minio bucket name was not found in configuration"); + + /// + public async Task> GetFileList() + { + var list = new List(); + var request = new ListObjectsArgs() + .WithBucket(_bucketName) + .WithPrefix("") + .WithRecursive(true); + logger.LogInformation("Запрашиваем список файлов в бакете {bucket}", _bucketName); + var responseList = client.ListObjectsEnumAsync(request); + + if (responseList == null) + logger.LogWarning("Получен пустой ответ от бакета {bucket}", _bucketName); + + await foreach (var response in responseList!) + list.Add(response.Key); + return list; + } + + /// + public async Task UploadFile(string fileData) + { + var rootNode = JsonNode.Parse(fileData) ?? throw new ArgumentException("Passed string is not a valid JSON"); + var id = rootNode["id"]?.GetValue() ?? throw new ArgumentException("Passed JSON has invalid structure"); + + var bytes = Encoding.UTF8.GetBytes(fileData); + using var stream = new MemoryStream(bytes); + stream.Seek(0, SeekOrigin.Begin); + + logger.LogInformation("Начинаем загрузку курса {file} в бакет {bucket}", id, _bucketName); + var request = new PutObjectArgs() + .WithBucket(_bucketName) + .WithStreamData(stream) + .WithObjectSize(bytes.Length) + .WithObject($"course_{id}.json"); + + var response = await client.PutObjectAsync(request); + + if (response.ResponseStatusCode != HttpStatusCode.OK) + { + logger.LogError("Не удалось загрузить курс {file}: {code}", id, response.ResponseStatusCode); + return false; + } + logger.LogInformation("Курс {file} успешно загружен в бакет {bucket}", id, _bucketName); + return true; + } + + /// + public async Task DownloadFile(string key) + { + logger.LogInformation("Начинаем скачивание файла {file} из бакета {bucket}", key, _bucketName); + + try + { + var memoryStream = new MemoryStream(); + + var request = new GetObjectArgs() + .WithBucket(_bucketName) + .WithObject(key) + .WithCallbackStream(async (stream, cancellationToken) => + { + await stream.CopyToAsync(memoryStream, cancellationToken); + memoryStream.Seek(0, SeekOrigin.Begin); + }); + + var response = await client.GetObjectAsync(request); + + if (response == null) + { + logger.LogError("Не удалось скачать файл {file}", key); + throw new InvalidOperationException($"Error occurred downloading {key} - object is null"); + } + using var reader = new StreamReader(memoryStream, Encoding.UTF8); + return JsonNode.Parse(reader.ReadToEnd()) ?? throw new InvalidOperationException("Downloaded document is not a valid JSON"); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при скачивании файла {file}", key); + throw; + } + } + + /// + public async Task EnsureBucketExists() + { + logger.LogInformation("Проверяем существование бакета {bucket}", _bucketName); + try + { + var request = new BucketExistsArgs() + .WithBucket(_bucketName); + + var exists = await client.BucketExistsAsync(request); + if (!exists) + { + logger.LogInformation("Создаём бакет {bucket}", _bucketName); + var createRequest = new MakeBucketArgs() + .WithBucket(_bucketName); + await client.MakeBucketAsync(createRequest); + return; + } + logger.LogInformation("Бакет {bucket} уже существует", _bucketName); + } + catch (Exception ex) + { + logger.LogError(ex, "Необработанная ошибка при проверке бакета {bucket}", _bucketName); + throw; + } + } +} diff --git a/Service.FileStorage/appsettings.Development.json b/Service.FileStorage/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Service.FileStorage/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Service.FileStorage/appsettings.json b/Service.FileStorage/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/Service.FileStorage/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git "a/\320\241ourseApp.AppHost.Test/IntegrationTest.cs" "b/\320\241ourseApp.AppHost.Test/IntegrationTest.cs" new file mode 100644 index 00000000..dd8e44e4 --- /dev/null +++ "b/\320\241ourseApp.AppHost.Test/IntegrationTest.cs" @@ -0,0 +1,174 @@ +using System.Text.Json; +using Aspire.Hosting; +using CourseApp.Domain.Entity; +using Microsoft.Extensions.Logging; +using Xunit.Abstractions; + +namespace СourseApp.AppHost.Test; + +/// +/// Интеграционные тесты для проверки микросервисного пайплайна: +/// API -> SQS -> FileStorage -> MinIO +/// +/// Служба журналирования юнит-тестов +public class IntegrationTest(ITestOutputHelper output) : IAsyncLifetime +{ + private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + + private IDistributedApplicationTestingBuilder? _builder; + private DistributedApplication? _app; + + /// + public async Task InitializeAsync() + { + var cancellationToken = CancellationToken.None; + _builder = await DistributedApplicationTestingBuilder.CreateAsync(cancellationToken); + _builder.Configuration["DcpPublisher:RandomizePorts"] = "false"; + _builder.Services.AddLogging(logging => + { + logging.AddXUnit(output); + logging.SetMinimumLevel(LogLevel.Debug); + logging.AddFilter("Aspire.Hosting.Dcp", LogLevel.Debug); + logging.AddFilter("Aspire.Hosting", LogLevel.Debug); + }); + } + + /// + /// Проверяет, что вызов гейтвея: + /// + /// В ответ отдаёт сгенерированный курс + /// Сериализует курс в MinIO через брокер SQS и файловый сервис + /// Данные, отданные клиенту и положенные в объектное хранилище, идентичны + /// + /// + [Fact] + public async Task ApiToStorageIntegrationTest() + { + var cancellationToken = CancellationToken.None; + _app = await _builder!.BuildAsync(cancellationToken); + await _app.StartAsync(cancellationToken); + + var id = new Random().Next(1, 100); + + using var gatewayClient = _app.CreateHttpClient("api-gateway", "http"); + using var gatewayResponse = await gatewayClient.GetAsync($"/course?id={id}"); + var apiCourse = JsonSerializer.Deserialize(await gatewayResponse.Content.ReadAsStringAsync(), _jsonOptions); + + await Task.Delay(5000); + + using var storageClient = _app.CreateHttpClient("service-filestorage", "http"); + using var listResponse = await storageClient.GetAsync("/api/files"); + var fileList = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync()); + using var fileResponse = await storageClient.GetAsync($"/api/files/course_{id}.json"); + var s3Course = JsonSerializer.Deserialize(await fileResponse.Content.ReadAsStringAsync(), _jsonOptions); + + Assert.NotNull(fileList); + Assert.Single(fileList); + Assert.Equal($"course_{id}.json", fileList[0]); + Assert.NotNull(apiCourse); + Assert.NotNull(s3Course); + Assert.Equal(id, s3Course.Id); + Assert.Equivalent(apiCourse, s3Course); + } + + /// + /// Проверяет, что повторный запрос курса с тем же id обслуживается из кэша + /// и не приводит к повторной публикации в брокер: в бакете остаётся ровно один файл. + /// + [Fact] + public async Task CacheHitDoesNotDuplicateStorageObjectTest() + { + var cancellationToken = CancellationToken.None; + _app = await _builder!.BuildAsync(cancellationToken); + await _app.StartAsync(cancellationToken); + + var id = new Random().Next(1, 100); + + using var gatewayClient = _app.CreateHttpClient("api-gateway", "http"); + using var firstResponse = await gatewayClient.GetAsync($"/course?id={id}"); + var firstCourse = JsonSerializer.Deserialize(await firstResponse.Content.ReadAsStringAsync(), _jsonOptions); + using var secondResponse = await gatewayClient.GetAsync($"/course?id={id}"); + var secondCourse = JsonSerializer.Deserialize(await secondResponse.Content.ReadAsStringAsync(), _jsonOptions); + + await Task.Delay(5000); + + using var storageClient = _app.CreateHttpClient("service-filestorage", "http"); + using var listResponse = await storageClient.GetAsync("/api/files"); + var fileList = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync()); + + Assert.NotNull(firstCourse); + Assert.NotNull(secondCourse); + Assert.Equivalent(firstCourse, secondCourse); + Assert.NotNull(fileList); + Assert.Single(fileList); + Assert.Equal($"course_{id}.json", fileList[0]); + } + + /// + /// Проверяет, что три запроса с разными идентификаторами создают три отдельных + /// файла в бакете, содержимое которых совпадает с ответами гейтвея. + /// + [Fact] + public async Task MultipleDistinctCoursesAreStoredTest() + { + var cancellationToken = CancellationToken.None; + _app = await _builder!.BuildAsync(cancellationToken); + await _app.StartAsync(cancellationToken); + + var ids = new[] { 11, 22, 33 }; + var apiCourses = new Dictionary(); + + using var gatewayClient = _app.CreateHttpClient("api-gateway", "http"); + foreach (var id in ids) + { + using var response = await gatewayClient.GetAsync($"/course?id={id}"); + var course = JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync(), _jsonOptions); + Assert.NotNull(course); + apiCourses[id] = course!; + } + + await Task.Delay(5000); + + using var storageClient = _app.CreateHttpClient("service-filestorage", "http"); + using var listResponse = await storageClient.GetAsync("/api/files"); + var fileList = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync()); + + Assert.NotNull(fileList); + Assert.Equal(ids.Length, fileList!.Count); + foreach (var id in ids) + Assert.Contains($"course_{id}.json", fileList); + + foreach (var id in ids) + { + using var fileResponse = await storageClient.GetAsync($"/api/files/course_{id}.json"); + var s3Course = JsonSerializer.Deserialize(await fileResponse.Content.ReadAsStringAsync(), _jsonOptions); + Assert.NotNull(s3Course); + Assert.Equal(id, s3Course!.Id); + Assert.Equivalent(apiCourses[id], s3Course); + } + } + + /// + /// Проверяет, что запрос несуществующего объекта из бакета завершается ошибкой. + /// + [Fact] + public async Task MissingStorageObjectReturnsErrorTest() + { + var cancellationToken = CancellationToken.None; + _app = await _builder!.BuildAsync(cancellationToken); + await _app.StartAsync(cancellationToken); + + using var storageClient = _app.CreateHttpClient("service-filestorage", "http"); + using var response = await storageClient.GetAsync("/api/files/course_99999.json"); + + Assert.False(response.IsSuccessStatusCode); + } + + /// + public async Task DisposeAsync() + { + await _app!.StopAsync(); + await _app.DisposeAsync(); + await _builder!.DisposeAsync(); + } +} diff --git "a/\320\241ourseApp.AppHost.Test/\320\241ourseApp.AppHost.Test.csproj" "b/\320\241ourseApp.AppHost.Test/\320\241ourseApp.AppHost.Test.csproj" new file mode 100644 index 00000000..9f27198c --- /dev/null +++ "b/\320\241ourseApp.AppHost.Test/\320\241ourseApp.AppHost.Test.csproj" @@ -0,0 +1,33 @@ + + + + net8.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 1c66ea8ddaebf73c46b23cb9b0b5e746d9a0cb2b Mon Sep 17 00:00:00 2001 From: Daryaskhrv Date: Tue, 28 Apr 2026 15:46:04 +0400 Subject: [PATCH 8/8] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D1=82=D0=B5=D1=81=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../IntegrationTest.cs" | 41 ++++++------------- 1 file changed, 13 insertions(+), 28 deletions(-) diff --git "a/\320\241ourseApp.AppHost.Test/IntegrationTest.cs" "b/\320\241ourseApp.AppHost.Test/IntegrationTest.cs" index dd8e44e4..4aa126e8 100644 --- "a/\320\241ourseApp.AppHost.Test/IntegrationTest.cs" +++ "b/\320\241ourseApp.AppHost.Test/IntegrationTest.cs" @@ -15,22 +15,24 @@ public class IntegrationTest(ITestOutputHelper output) : IAsyncLifetime { private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; - private IDistributedApplicationTestingBuilder? _builder; private DistributedApplication? _app; /// public async Task InitializeAsync() { var cancellationToken = CancellationToken.None; - _builder = await DistributedApplicationTestingBuilder.CreateAsync(cancellationToken); - _builder.Configuration["DcpPublisher:RandomizePorts"] = "false"; - _builder.Services.AddLogging(logging => + var builder = await DistributedApplicationTestingBuilder + .CreateAsync(cancellationToken); + builder.Configuration["DcpPublisher:RandomizePorts"] = "false"; + builder.Services.AddLogging(logging => { logging.AddXUnit(output); logging.SetMinimumLevel(LogLevel.Debug); logging.AddFilter("Aspire.Hosting.Dcp", LogLevel.Debug); logging.AddFilter("Aspire.Hosting", LogLevel.Debug); }); + _app = await builder.BuildAsync(cancellationToken); + await _app.StartAsync(cancellationToken); } /// @@ -44,19 +46,15 @@ public async Task InitializeAsync() [Fact] public async Task ApiToStorageIntegrationTest() { - var cancellationToken = CancellationToken.None; - _app = await _builder!.BuildAsync(cancellationToken); - await _app.StartAsync(cancellationToken); - var id = new Random().Next(1, 100); - using var gatewayClient = _app.CreateHttpClient("api-gateway", "http"); + using var gatewayClient = _app!.CreateHttpClient("api-gateway", "http"); using var gatewayResponse = await gatewayClient.GetAsync($"/course?id={id}"); var apiCourse = JsonSerializer.Deserialize(await gatewayResponse.Content.ReadAsStringAsync(), _jsonOptions); await Task.Delay(5000); - using var storageClient = _app.CreateHttpClient("service-filestorage", "http"); + using var storageClient = _app!.CreateHttpClient("service-filestorage", "http"); using var listResponse = await storageClient.GetAsync("/api/files"); var fileList = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync()); using var fileResponse = await storageClient.GetAsync($"/api/files/course_{id}.json"); @@ -78,13 +76,9 @@ public async Task ApiToStorageIntegrationTest() [Fact] public async Task CacheHitDoesNotDuplicateStorageObjectTest() { - var cancellationToken = CancellationToken.None; - _app = await _builder!.BuildAsync(cancellationToken); - await _app.StartAsync(cancellationToken); - var id = new Random().Next(1, 100); - using var gatewayClient = _app.CreateHttpClient("api-gateway", "http"); + using var gatewayClient = _app!.CreateHttpClient("api-gateway", "http"); using var firstResponse = await gatewayClient.GetAsync($"/course?id={id}"); var firstCourse = JsonSerializer.Deserialize(await firstResponse.Content.ReadAsStringAsync(), _jsonOptions); using var secondResponse = await gatewayClient.GetAsync($"/course?id={id}"); @@ -92,7 +86,7 @@ public async Task CacheHitDoesNotDuplicateStorageObjectTest() await Task.Delay(5000); - using var storageClient = _app.CreateHttpClient("service-filestorage", "http"); + using var storageClient = _app!.CreateHttpClient("service-filestorage", "http"); using var listResponse = await storageClient.GetAsync("/api/files"); var fileList = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync()); @@ -111,14 +105,10 @@ public async Task CacheHitDoesNotDuplicateStorageObjectTest() [Fact] public async Task MultipleDistinctCoursesAreStoredTest() { - var cancellationToken = CancellationToken.None; - _app = await _builder!.BuildAsync(cancellationToken); - await _app.StartAsync(cancellationToken); - var ids = new[] { 11, 22, 33 }; var apiCourses = new Dictionary(); - using var gatewayClient = _app.CreateHttpClient("api-gateway", "http"); + using var gatewayClient = _app!.CreateHttpClient("api-gateway", "http"); foreach (var id in ids) { using var response = await gatewayClient.GetAsync($"/course?id={id}"); @@ -129,7 +119,7 @@ public async Task MultipleDistinctCoursesAreStoredTest() await Task.Delay(5000); - using var storageClient = _app.CreateHttpClient("service-filestorage", "http"); + using var storageClient = _app!.CreateHttpClient("service-filestorage", "http"); using var listResponse = await storageClient.GetAsync("/api/files"); var fileList = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync()); @@ -154,11 +144,7 @@ public async Task MultipleDistinctCoursesAreStoredTest() [Fact] public async Task MissingStorageObjectReturnsErrorTest() { - var cancellationToken = CancellationToken.None; - _app = await _builder!.BuildAsync(cancellationToken); - await _app.StartAsync(cancellationToken); - - using var storageClient = _app.CreateHttpClient("service-filestorage", "http"); + using var storageClient = _app!.CreateHttpClient("service-filestorage", "http"); using var response = await storageClient.GetAsync("/api/files/course_99999.json"); Assert.False(response.IsSuccessStatusCode); @@ -169,6 +155,5 @@ public async Task DisposeAsync() { await _app!.StopAsync(); await _app.DisposeAsync(); - await _builder!.DisposeAsync(); } }