diff --git a/Api.Gateway/Api.Gateway.csproj b/Api.Gateway/Api.Gateway.csproj new file mode 100644 index 00000000..77ce9775 --- /dev/null +++ b/Api.Gateway/Api.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + \ No newline at end of file diff --git a/Api.Gateway/LoadBalancers/WeightedRandom.cs b/Api.Gateway/LoadBalancers/WeightedRandom.cs new file mode 100644 index 00000000..0f495f89 --- /dev/null +++ b/Api.Gateway/LoadBalancers/WeightedRandom.cs @@ -0,0 +1,46 @@ +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 readonly int[] _weights = configuration + .GetSection("WeightedRandom:Weights") + .Get() ?? [1, 1, 1, 1, 1]; + + public string Type => nameof(WeightedRandom); + + public async Task> LeaseAsync(HttpContext httpContext) + { + var serviceList = await services(); + + if (serviceList.Count == 0) + throw new InvalidOperationException("Нет доступных сервисов"); + + 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++) + { + 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/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 661f1181..70343b3d 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №3 Интеграционное тестирование + Вариант №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 d1fe7ab3..e8ac606e 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7186/course" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..3dabb63e 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -1,10 +1,24 @@  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 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 +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 @@ -15,6 +29,34 @@ 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 + {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 + {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/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..c24a76ad --- /dev/null +++ b/CourseApp.Api/CourseApp.Api.csproj @@ -0,0 +1,23 @@ + + + + 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 new file mode 100644 index 00000000..746bc78c --- /dev/null +++ b/CourseApp.Api/Program.cs @@ -0,0 +1,35 @@ +using Amazon.SQS; +using CourseApp.Api.Messaging; +using CourseApp.Api.Services; +using CourseApp.ServiceDefaults; +using LocalStack.Client.Extensions; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +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()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapDefaultEndpoints(); +app.UseHttpsRedirection(); +app.UseAuthorization(); +app.MapControllers(); +app.Run(); 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..54439ae2 --- /dev/null +++ b/CourseApp.Api/Services/CourseGenerator.cs @@ -0,0 +1,46 @@ +using Bogus; +using CourseApp.Domain.Entity; + +namespace CourseApp.Api.Services; + +/// +/// Генератор тестовых данных при отсутствии данных в кэше +/// +public class CourseGenerator +{ + private static readonly string[] _courseNames = + [ + "C# для начинающих", + "Python для анализа данных", + "Микросервисная архитектура", + "Docker", + "Алгоритмы и структуры данных", + "SQL и базы данных", + "Автоматизированное тестирование", + "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 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 new file mode 100644 index 00000000..60024f46 --- /dev/null +++ b/CourseApp.Api/Services/CourseService.cs @@ -0,0 +1,68 @@ +using System.Text.Json; +using CourseApp.Api.Messaging; +using CourseApp.Domain.Entity; +using Microsoft.Extensions.Caching.Distributed; + +namespace CourseApp.Api.Services; + +/// +/// Сервис для получения информации о курсе +/// +public class CourseService(IDistributedCache _cache, IConfiguration _configuration, + ILogger _logger, CourseGenerator _generator, + IProducerService _producer) +{ + /// + /// Получает курс по идентификатору из кэша или с помощью генератора + /// + 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); + + await _producer.SendMessage(course); + + try + { + 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); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Не удалось сохранить курс {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..6ae5266d --- /dev/null +++ b/CourseApp.AppHost/AppHost.cs @@ -0,0 +1,52 @@ +using Amazon; +using Aspire.Hosting.LocalStack.Container; + +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisCommander(); + +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); +} + +builder.AddProject("client") + .WaitFor(gateway); + +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 new file mode 100644 index 00000000..30d0403a --- /dev/null +++ b/CourseApp.AppHost/CourseApp.AppHost.csproj @@ -0,0 +1,37 @@ + + + + + + Exe + net8.0 + enable + enable + c086dba3-3e81-4540-916e-ccad1674fa30 + + + + + + + + + + + + + + + + + + + Always + + + + + + + + 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..a6b256bb --- /dev/null +++ b/CourseApp.AppHost/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "LocalStack": { + "UseLocalStack": true + } +} 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..29530a72 --- /dev/null +++ b/CourseApp.Domain/Entity/CourseApp.cs @@ -0,0 +1,60 @@ +using System.Text.Json.Serialization; + +namespace CourseApp.Domain.Entity; + +/// +/// Модель учебного курса +/// +public class Course +{ + /// + /// Идентификатор курса в системе + /// + [JsonPropertyName("id")] + 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..f1484c37 --- /dev/null +++ b/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj @@ -0,0 +1,25 @@ + + + + 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 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 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..4aa126e8 --- /dev/null +++ "b/\320\241ourseApp.AppHost.Test/IntegrationTest.cs" @@ -0,0 +1,159 @@ +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 DistributedApplication? _app; + + /// + public async Task InitializeAsync() + { + var cancellationToken = CancellationToken.None; + 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); + } + + /// + /// Проверяет, что вызов гейтвея: + /// + /// В ответ отдаёт сгенерированный курс + /// Сериализует курс в MinIO через брокер SQS и файловый сервис + /// Данные, отданные клиенту и положенные в объектное хранилище, идентичны + /// + /// + [Fact] + public async Task ApiToStorageIntegrationTest() + { + 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 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 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() + { + 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(); + } +} 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