diff --git a/Api.Gateway/Api.Gateway.csproj b/Api.Gateway/Api.Gateway.csproj new file mode 100644 index 00000000..159f391a --- /dev/null +++ b/Api.Gateway/Api.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/Api.Gateway/Program.cs b/Api.Gateway/Program.cs new file mode 100644 index 00000000..f742bfe0 --- /dev/null +++ b/Api.Gateway/Program.cs @@ -0,0 +1,32 @@ +using Api.Gateway; +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())); + +var allowedOrigins = builder.Configuration + .GetSection("Cors:AllowedOrigins") + .Get() ?? []; + +builder.Services.AddCors(options => + options.AddDefaultPolicy(policy => + policy.WithOrigins(allowedOrigins) + .WithMethods("GET") + .AllowAnyHeader())); + +var app = builder.Build(); + +app.UseCors(); + +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..6d69bf64 --- /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:48792", + "sslPort": 44345 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5252", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7032;http://localhost:5252", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Api.Gateway/WeightedRandom.cs b/Api.Gateway/WeightedRandom.cs new file mode 100644 index 00000000..8fdcb2ea --- /dev/null +++ b/Api.Gateway/WeightedRandom.cs @@ -0,0 +1,56 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace Api.Gateway; + +/// +/// Балансировщик нагрузки «Взвешенный случайный выбор» (Weighted Random). +/// Каждой реплике присваивается целочисленный вес из секции LoadBalancer:Weights. +/// При поступлении запроса реплика выбирается случайно — вероятность выбора пропорциональна весу +/// (вес реплики / сумма всех весов). +/// +/// Делегат для получения списка доступных реплик сервиса. +/// +/// Конфигурация приложения с секцией LoadBalancer:Weights — +/// массив int, где индекс соответствует номеру реплики, а значение — относительному весу. +/// +public class WeightedRandom( + Func>> services, + IConfiguration configuration) : ILoadBalancer +{ + public string Type => nameof(WeightedRandom); + + private readonly int[] _weights = configuration.GetSection("LoadBalancer:Weights").Get() ?? []; + + public async Task> LeaseAsync(HttpContext context) + { + var pool = await services(); + + if (pool.Count == 0) + throw new InvalidOperationException("No available downstream services"); + + var total = 0; + for (var i = 0; i < pool.Count; i++) + total += Weight(i); + + var value = Random.Shared.Next(total); + + for (var i = 0; i < pool.Count; i++) + { + value -= Weight(i); + if (value < 0) + return new OkResponse(pool[i].HostAndPort); + } + + return new OkResponse(pool[^1].HostAndPort); + } + + public void Release(ServiceHostAndPort hostAndPort) { } + + /// + /// Возвращает вес реплики по индексу. + /// Если вес не задан или не положителен — возвращает 1. + /// + private int Weight(int i) => i < _weights.Length && _weights[i] > 0 ? _weights[i] : 1; +} 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..681f7049 --- /dev/null +++ b/Api.Gateway/appsettings.json @@ -0,0 +1,18 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "Cors": { + "AllowedOrigins": [ + "http://localhost:5127", + "https://localhost:7282" + ] + }, + "LoadBalancer": { + "Weights": [ 35, 25, 20, 12, 8 ] + }, + "AllowedHosts": "*" +} diff --git a/Api.Gateway/ocelot.json b/Api.Gateway/ocelot.json new file mode 100644 index 00000000..60f1f96e --- /dev/null +++ b/Api.Gateway/ocelot.json @@ -0,0 +1,20 @@ +{ + "Routes": [ + { + "DownstreamPathTemplate": "/api/warehouse-item", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { "Host": "localhost", "Port": 7250 }, + { "Host": "localhost", "Port": 7251 }, + { "Host": "localhost", "Port": 7252 }, + { "Host": "localhost", "Port": 7253 }, + { "Host": "localhost", "Port": 7254 } + ], + "UpstreamPathTemplate": "/warehouse-item", + "UpstreamHttpMethod": [ "GET" ], + "LoadBalancerOptions": { + "Type": "WeightedRandom" + } + } + ] +} diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..2d70aabd 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №3 "Интеграционное тестирование" + Вариант №31 "Товар на складе" + Выполнил Пахомов Леонид 6512 + Ссылка на форк 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..cb2c9b92 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7032/warehouse-item" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..56ac03e6 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,6 +5,18 @@ VisualStudioVersion = 17.14.36811.4 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseApp.AppHost", "WarehouseApp\WarehouseApp.AppHost\WarehouseApp.AppHost.csproj", "{62DA23FA-2BAF-4F9A-B719-B4EE06809BA0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseApp.ServiceDefaults", "WarehouseApp\WarehouseApp.ServiceDefaults\WarehouseApp.ServiceDefaults.csproj", "{ADCEFD5A-DE46-3D8E-DD7F-B5FD83A993DF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseApp.Api", "WarehouseApp.Api\WarehouseApp.Api.csproj", "{6D2468DE-58C5-E4A1-2839-0E91AF620D88}" +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}") = "WarehouseApp.AppHost.Tests", "WarehouseApp\WarehouseApp.AppHost.Tests\WarehouseApp.AppHost.Tests.csproj", "{088F0F74-E266-4C3E-8A9E-CE08D81DC5A6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseApp.FileService", "WarehouseApp.FileService\WarehouseApp.FileService.csproj", "{8977908D-CDF3-D729-11A1-88FB4F7E61E5}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +27,30 @@ 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 + {62DA23FA-2BAF-4F9A-B719-B4EE06809BA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {62DA23FA-2BAF-4F9A-B719-B4EE06809BA0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {62DA23FA-2BAF-4F9A-B719-B4EE06809BA0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {62DA23FA-2BAF-4F9A-B719-B4EE06809BA0}.Release|Any CPU.Build.0 = Release|Any CPU + {ADCEFD5A-DE46-3D8E-DD7F-B5FD83A993DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ADCEFD5A-DE46-3D8E-DD7F-B5FD83A993DF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ADCEFD5A-DE46-3D8E-DD7F-B5FD83A993DF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ADCEFD5A-DE46-3D8E-DD7F-B5FD83A993DF}.Release|Any CPU.Build.0 = Release|Any CPU + {6D2468DE-58C5-E4A1-2839-0E91AF620D88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6D2468DE-58C5-E4A1-2839-0E91AF620D88}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6D2468DE-58C5-E4A1-2839-0E91AF620D88}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6D2468DE-58C5-E4A1-2839-0E91AF620D88}.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 + {088F0F74-E266-4C3E-8A9E-CE08D81DC5A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {088F0F74-E266-4C3E-8A9E-CE08D81DC5A6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {088F0F74-E266-4C3E-8A9E-CE08D81DC5A6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {088F0F74-E266-4C3E-8A9E-CE08D81DC5A6}.Release|Any CPU.Build.0 = Release|Any CPU + {8977908D-CDF3-D729-11A1-88FB4F7E61E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8977908D-CDF3-D729-11A1-88FB4F7E61E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8977908D-CDF3-D729-11A1-88FB4F7E61E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8977908D-CDF3-D729-11A1-88FB4F7E61E5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/README.md b/README.md index dcaa5eb7..206098b5 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,101 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](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). +# Лабораторная работа №1 — «Кэширование» +Реализация сервиса генерации данных о товарах на складе с кэшированием ответов через Redis, оркестрацией через .NET Aspire и Blazor WebAssembly клиентом. + +## Стек технологий + +| Технология | Назначение | +|---|---| +| .NET 8 | Серверная часть | +| ASP.NET Core Minimal API | HTTP-сервис | +| .NET Aspire | Оркестрация сервисов | +| Redis + `IDistributedCache` | Распределённое кэширование | +| Bogus | Генерация тестовых данных | +| Blazor WebAssembly | Клиентское приложение | + +## API + +**Endpoint**: `GET /api/warehouse-item?id={int}` + +При первом запросе генерирует товар и кэширует его. При повторном запросе с тем же `id` возвращает данные из кэша. Время жизни записи в кэше настраивается через `CacheExpirationMinutes` в `appsettings.json` (по умолчанию 10 минут). + +**Пример ответа**: + +```json +{ + "id": 42, + "productName": "Fantastic Metal Shoes", + "category": "Electronics", + "quantity": 317, + "pricePerUnit": 1234.56, + "weightPerUnit": 2.45, + "dimensions": "30х15х10 см", + "isFragile": false, + "lastDeliveryDate": "2024-11-03", + "nextDeliveryDate": "2025-06-18" +} +``` + +## Сущность «Товар на складе» + +| № | Поле | Тип | Правило генерации | +|---|---|---|---| +| 1 | `id` | `int` | Передаётся из запроса | +| 2 | `productName` | `string` | `Commerce.ProductName()` | +| 3 | `category` | `string` | `Commerce.Categories(1)[0]` | +| 4 | `quantity` | `int` | Случайное `[0, 1000]` | +| 5 | `pricePerUnit` | `decimal` | Случайное `[1, 10000]`, 2 знака | +| 6 | `weightPerUnit` | `double` | Случайное `[0.1, 500]`, 2 знака | +| 7 | `dimensions` | `string` | Формат `**х**х** см` | +| 8 | `isFragile` | `bool` | Случайный `bool` | +| 9 | `lastDeliveryDate` | `DateOnly` | Прошедшая дата ≤ сегодня | +| 10 | `nextDeliveryDate` | `DateOnly` | Дата ≥ `lastDeliveryDate` | + +--- + +# Лабораторная работа №2 — «Балансировка нагрузки» + +Реализация API-шлюза на основе Ocelot с кастомным алгоритмом балансировки нагрузки **Weighted Random** (взвешенный случайный выбор). + +## Что было сделано + +1. **Оркестрация реплик** — в `AppHost.cs` настроен запуск 5 реплик сервиса генерации (`warehouseapp-api-0`…`warehouseapp-api-4`) на портах 7250–7254. +2. **API-шлюз на Ocelot** — проект `Api.Gateway` принимает клиентские запросы и маршрутизирует их к репликам через конфигурацию `ocelot.json`. +3. **Кастомный балансировщик `WeightedRandom`** — реализован алгоритм взвешенного случайного выбора реплики. + +## Алгоритм Weighted Random + +Каждой реплике присваивается целочисленный вес. При поступлении запроса вероятность выбора реплики пропорциональна её весу: + +$$P_i = \frac{w_i}{\sum_{j} w_j}$$ + +## Конфигурация весов + +Веса задаются в `Api.Gateway/appsettings.json` в секции `LoadBalancer:Weights` — массив целых чисел, где индекс соответствует номеру реплики: + +```json +{ + "LoadBalancer": { + "Weights": [ 35, 25, 20, 12, 8 ] + } +} +``` + +--- + +# Лабораторная работа №3 — «Брокер сообщений и объектное хранилище» + +Вариант: SNS + Minio. После генерации товар публикуется в SNS-топик в LocalStack, файловый сервис принимает уведомление по HTTP и кладёт JSON в бакет Minio. + +## Что было сделано + +1. CloudFormation-шаблон `WarehouseApp.AppHost/CloudFormation/warehouse-template-sns.yaml` с одним SNS-топиком `warehouse-topic`. В AppHost применяется через `AddAWSCloudFormationTemplate`. +2. В `AppHost.cs` подняты контейнеры `warehouse-localstack` (порт 4566) и `warehouse-minio`. Реплики API и файловый сервис получают AWS-конфигурацию через `WithReference(awsResources)`. +3. В `WarehouseApp.Api` после промаха кэша `WarehouseItemService` вызывает `SnsPublisherService.PublishAsync` — сериализует `WarehouseItem` и публикует в топик. ARN читается из `AWS:Resources:SNSTopicArn` (заполняется outputs CloudFormation). +4. `WarehouseApp.FileService`: + - на старте создаёт бакет (`S3MinioService.EnsureBucketExists`) и подписывает свой HTTP-эндпоинт на топик (`SnsSubscriptionService.SubscribeEndpoint`); + - `POST /api/sns` — вебхук, подтверждает `SubscriptionConfirmation` и сохраняет `Notification` в Minio под ключом `warehouse_{id}.json`; + - `GET /api/s3` и `GET /api/s3/{key}` — список ключей и чтение одного объекта. +5. Интеграционные тесты: + - `GatewayCall_ProducesFileInS3WithSameId` — дёргает `GET /warehouse-item?id={id}` у шлюза и поллит `GET /api/s3/warehouse_{id}.json` у файлового сервиса, сравнивая содержимое; + - `MultipleGatewayCalls_ProduceDistinctFilesInS3` — делает три запроса с разными id и проверяет, что все три ключа появились в `GET /api/s3`. diff --git a/WarehouseApp.Api/Generation/WarehouseItemGenerator.cs b/WarehouseApp.Api/Generation/WarehouseItemGenerator.cs new file mode 100644 index 00000000..a2b41f1a --- /dev/null +++ b/WarehouseApp.Api/Generation/WarehouseItemGenerator.cs @@ -0,0 +1,37 @@ +using Bogus; +using WarehouseApp.Api.Models; + +namespace WarehouseApp.Api.Generation; + +/// +/// Генератор товаров на складе на основе Bogus +/// +public static class WarehouseItemGenerator +{ + private static readonly Faker _faker = new Faker() + .RuleFor(x => x.ProductName, f => f.Commerce.ProductName()) + .RuleFor(x => x.Category, f => f.Commerce.Categories(1)[0]) + .RuleFor(x => x.Quantity, f => f.Random.Int(0, 1000)) + .RuleFor(x => x.PricePerUnit, f => Math.Round(f.Random.Decimal(1m, 10000m), 2)) + .RuleFor(x => x.WeightPerUnit, f => Math.Round(f.Random.Double(0.1, 500.0), 2)) + .RuleFor(x => x.Dimensions, f => + $"{f.Random.Int(1, 99)}х{f.Random.Int(1, 99)}х{f.Random.Int(1, 99)} см") + .RuleFor(x => x.IsFragile, f => f.Random.Bool()) + .RuleFor(x => x.LastDeliveryDate, f => + DateOnly.FromDateTime(f.Date.Past(2, DateTime.Today))) + .RuleFor(x => x.NextDeliveryDate, (f, item) => + f.Date.BetweenDateOnly(item.LastDeliveryDate, DateOnly.FromDateTime(DateTime.Today.AddYears(1))) + ); + + /// + /// Генерирует товар на складе с указанным идентификатором + /// + /// Идентификатор товара в системе + /// Сгенерированный товар на складе + public static WarehouseItem Generate(int id) + { + var item = _faker.Generate(); + item.Id = id; + return item; + } +} diff --git a/WarehouseApp.Api/Models/WarehouseItem.cs b/WarehouseApp.Api/Models/WarehouseItem.cs new file mode 100644 index 00000000..a396489e --- /dev/null +++ b/WarehouseApp.Api/Models/WarehouseItem.cs @@ -0,0 +1,57 @@ +namespace WarehouseApp.Api.Models; + +/// +/// Товар на складе +/// +public class WarehouseItem +{ + /// + /// Идентификатор в системе + /// + public int Id { get; set; } + + /// + /// Наименование товара + /// + public required string ProductName { get; init; } + + /// + /// Категория товара + /// + public required string Category { get; init; } + + /// + /// Количество на складе + /// + public int Quantity { get; init; } + + /// + /// Цена за единицу товара + /// + public decimal PricePerUnit { get; init; } + + /// + /// Вес единицы товара + /// + public double WeightPerUnit { get; init; } + + /// + /// Габариты единицы товара + /// + public required string Dimensions { get; init; } + + /// + /// Товар хрупкий + /// + public bool IsFragile { get; init; } + + /// + /// Дата последней поставки + /// + public DateOnly LastDeliveryDate { get; init; } + + /// + /// Дата следующей поставки + /// + public DateOnly NextDeliveryDate { get; init; } +} diff --git a/WarehouseApp.Api/Program.cs b/WarehouseApp.Api/Program.cs new file mode 100644 index 00000000..e44c79e0 --- /dev/null +++ b/WarehouseApp.Api/Program.cs @@ -0,0 +1,23 @@ +using Amazon.SimpleNotificationService; +using LocalStack.Client.Extensions; +using WarehouseApp.Api.Services; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("cache"); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); + +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +app.MapGet("/api/warehouse-item", async (int id, IWarehouseItemService service) => + Results.Ok(await service.GetOrGenerate(id))); + +app.Run(); diff --git a/WarehouseApp.Api/Properties/launchSettings.json b/WarehouseApp.Api/Properties/launchSettings.json new file mode 100644 index 00000000..1c771b97 --- /dev/null +++ b/WarehouseApp.Api/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:15575", + "sslPort": 44317 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5288", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7284;http://localhost:5288", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/WarehouseApp.Api/Services/ISnsPublisherService.cs b/WarehouseApp.Api/Services/ISnsPublisherService.cs new file mode 100644 index 00000000..b6f4353f --- /dev/null +++ b/WarehouseApp.Api/Services/ISnsPublisherService.cs @@ -0,0 +1,15 @@ +using WarehouseApp.Api.Models; + +namespace WarehouseApp.Api.Services; + +/// +/// Сервис публикации товара в SNS-топик +/// +public interface ISnsPublisherService +{ + /// + /// Публикует сериализованный товар в SNS-топик + /// + /// Товар на складе + public Task PublishAsync(WarehouseItem item); +} diff --git a/WarehouseApp.Api/Services/IWarehouseItemService.cs b/WarehouseApp.Api/Services/IWarehouseItemService.cs new file mode 100644 index 00000000..6221742e --- /dev/null +++ b/WarehouseApp.Api/Services/IWarehouseItemService.cs @@ -0,0 +1,16 @@ +using WarehouseApp.Api.Models; + +namespace WarehouseApp.Api.Services; + +/// +/// Сервис получения товара на складе с кэшированием +/// +public interface IWarehouseItemService +{ + /// + /// Возвращает товар по идентификатору: из кэша или генерирует новый + /// + /// Идентификатор товара в системе + /// Сгенерированный товар на складе + public Task GetOrGenerate(int id); +} diff --git a/WarehouseApp.Api/Services/SnsPublisherService.cs b/WarehouseApp.Api/Services/SnsPublisherService.cs new file mode 100644 index 00000000..16c2da36 --- /dev/null +++ b/WarehouseApp.Api/Services/SnsPublisherService.cs @@ -0,0 +1,43 @@ +using System.Net; +using System.Text.Json; +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; +using WarehouseApp.Api.Models; + +namespace WarehouseApp.Api.Services; + +/// +/// Клиент SNS +/// Конфигурация приложения +/// Логгер +public class SnsPublisherService( + IAmazonSimpleNotificationService client, + IConfiguration configuration, + ILogger logger) : ISnsPublisherService +{ + private readonly string _topicArn = configuration["AWS:Resources:SNSTopicArn"] + ?? throw new KeyNotFoundException("SNS topic ARN was not found in configuration"); + + /// + public async Task PublishAsync(WarehouseItem item) + { + try + { + var json = JsonSerializer.Serialize(item); + var request = new PublishRequest + { + Message = json, + TopicArn = _topicArn + }; + var response = await client.PublishAsync(request); + if (response.HttpStatusCode == HttpStatusCode.OK) + logger.LogInformation("Warehouse item {Id} was published to SNS", item.Id); + else + throw new InvalidOperationException($"SNS returned {response.HttpStatusCode}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Unable to publish warehouse item {Id} to SNS topic", item.Id); + } + } +} diff --git a/WarehouseApp.Api/Services/WarehouseItemService.cs b/WarehouseApp.Api/Services/WarehouseItemService.cs new file mode 100644 index 00000000..a589730f --- /dev/null +++ b/WarehouseApp.Api/Services/WarehouseItemService.cs @@ -0,0 +1,87 @@ +using System.Text.Json; +using Microsoft.Extensions.Caching.Distributed; +using WarehouseApp.Api.Generation; +using WarehouseApp.Api.Models; + +namespace WarehouseApp.Api.Services; + +/// +/// Кэш +/// Служба публикации в SNS +/// Логгер +/// Конфигурация приложения +public class WarehouseItemService( + IDistributedCache cache, + ISnsPublisherService publisher, + ILogger logger, + IConfiguration configuration) + : IWarehouseItemService +{ + private const string KeyPrefix = "warehouse-item:"; + + private readonly int _cacheExpirationMinutes = configuration.GetValue("CacheExpirationMinutes", 10); + + /// + public async Task GetOrGenerate(int id) + { + var cached = await TryGetFromCache(id); + if (cached is not null) + return cached; + + logger.LogInformation("Cache miss for item {Id}, generating...", id); + + var item = WarehouseItemGenerator.Generate(id); + logger.LogInformation("Successfully generated item {Id}", id); + + await publisher.PublishAsync(item); + await TrySaveToCache(id, item); + return item; + } + + /// + /// Пытается получить товар из кэша + /// + /// Идентификатор товара в системе + /// Товар из кэша или , если запись отсутствует или произошла ошибка + private async Task TryGetFromCache(int id) + { + try + { + var data = await cache.GetStringAsync(KeyPrefix + id); + + if (data is null) + return null; + + logger.LogInformation("Cache hit for item {Id}", id); + return JsonSerializer.Deserialize(data); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get item {Id} from cache: {Error}", id, ex.Message); + return null; + } + } + + /// + /// Сохраняет товар в кэш + /// + /// Идентификатор товара в системе + /// Товар для сохранения + private async Task TrySaveToCache(int id, WarehouseItem item) + { + try + { + var data = JsonSerializer.Serialize(item); + await cache.SetStringAsync(KeyPrefix + id, data, new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_cacheExpirationMinutes) + }); + + logger.LogInformation("Item {Id} saved to cache", id); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to save item {Id} to cache: {Error}", id, ex.Message); + } + } +} diff --git a/WarehouseApp.Api/WarehouseApp.Api.csproj b/WarehouseApp.Api/WarehouseApp.Api.csproj new file mode 100644 index 00000000..7ffe6dfb --- /dev/null +++ b/WarehouseApp.Api/WarehouseApp.Api.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/WarehouseApp.Api/appsettings.Development.json b/WarehouseApp.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/WarehouseApp.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/WarehouseApp.Api/appsettings.json b/WarehouseApp.Api/appsettings.json new file mode 100644 index 00000000..5165d1bb --- /dev/null +++ b/WarehouseApp.Api/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "CacheExpirationMinutes": 10, + "AllowedHosts": "*" +} diff --git a/WarehouseApp.FileService/Controllers/S3StorageController.cs b/WarehouseApp.FileService/Controllers/S3StorageController.cs new file mode 100644 index 00000000..813f0542 --- /dev/null +++ b/WarehouseApp.FileService/Controllers/S3StorageController.cs @@ -0,0 +1,64 @@ +using System.Text; +using System.Text.Json.Nodes; +using Microsoft.AspNetCore.Mvc; +using WarehouseApp.FileService.Storage; + +namespace WarehouseApp.FileService.Controllers; + +/// +/// Контроллер для чтения файлов из S3-бакета +/// +/// Служба для работы с S3 +/// Логгер +[ApiController] +[Route("api/s3")] +public class S3StorageController( + IS3Service s3Service, + ILogger logger) : ControllerBase +{ + /// + /// Возвращает список ключей файлов в бакете + /// + [HttpGet] + [ProducesResponseType(200)] + [ProducesResponseType(500)] + public async Task>> ListFiles() + { + logger.LogInformation("Method {Method} was called", nameof(ListFiles)); + try + { + var list = await s3Service.GetFileList(); + logger.LogInformation("Got a list of {Count} files from bucket", list.Count); + return Ok(list); + } + catch (Exception ex) + { + logger.LogError(ex, "Exception occurred during {Method}", nameof(ListFiles)); + return BadRequest(ex.Message); + } + } + + /// + /// Возвращает JSON-документ по ключу + /// + /// Ключ файла в бакете + [HttpGet("{key}")] + [ProducesResponseType(200)] + [ProducesResponseType(500)] + public async Task> GetFile(string key) + { + logger.LogInformation("Method {Method} was called with key {Key}", nameof(GetFile), key); + try + { + var node = await s3Service.DownloadFile(key); + logger.LogInformation("Received json of {Size} bytes", + Encoding.UTF8.GetByteCount(node.ToJsonString())); + return Ok(node); + } + catch (Exception ex) + { + logger.LogError(ex, "Exception occurred during {Method}", nameof(GetFile)); + return BadRequest(ex.Message); + } + } +} diff --git a/WarehouseApp.FileService/Controllers/SnsSubscriberController.cs b/WarehouseApp.FileService/Controllers/SnsSubscriberController.cs new file mode 100644 index 00000000..2a701979 --- /dev/null +++ b/WarehouseApp.FileService/Controllers/SnsSubscriberController.cs @@ -0,0 +1,77 @@ +using System.Text; +using Amazon.SimpleNotificationService.Util; +using Microsoft.AspNetCore.Mvc; +using WarehouseApp.FileService.Storage; + +namespace WarehouseApp.FileService.Controllers; + +/// +/// Контроллер для приёма SNS-уведомлений и подтверждения подписки +/// +/// Служба для работы с S3 +/// Конфигурация +/// Логгер +[ApiController] +[Route("api/sns")] +public class SnsSubscriberController( + IS3Service s3Service, + IConfiguration configuration, + ILogger logger) : ControllerBase +{ + private readonly string _localstackHost = configuration["AWS:Resources:LocalStackHost"] + ?? throw new KeyNotFoundException("LocalStack host was not found in configuration"); + + private readonly int _localstackPort = configuration.GetValue("AWS:Resources:LocalStackPort") + ?? throw new KeyNotFoundException("LocalStack port was not found in configuration"); + + /// + /// Вебхук для приёма сообщений из SNS-топика. Также используется + /// для подтверждения подписки при инициализации информационного обмена + /// + /// В любом случае возвращает 200 + [HttpPost] + [ProducesResponseType(200)] + public async Task ReceiveMessage() + { + logger.LogInformation("SNS webhook was called"); + try + { + using var reader = new StreamReader(Request.Body, Encoding.UTF8); + var jsonContent = await reader.ReadToEndAsync(); + + var snsMessage = Message.ParseMessage(jsonContent); + + if (snsMessage.Type == "SubscriptionConfirmation") + { + logger.LogInformation("SubscriptionConfirmation was received"); + using var httpClient = new HttpClient(); + var builder = new UriBuilder(new Uri(snsMessage.SubscribeURL)) + { + Scheme = "http", + Host = _localstackHost, + Port = _localstackPort + }; + var response = await httpClient.GetAsync(builder.Uri); + if (!response.IsSuccessStatusCode) + { + var body = await response.Content.ReadAsStringAsync(); + throw new InvalidOperationException( + $"SubscriptionConfirmation returned {response.StatusCode}: {body}"); + } + logger.LogInformation("Subscription was successfully confirmed"); + return Ok(); + } + + if (snsMessage.Type == "Notification") + { + await s3Service.UploadFile(snsMessage.MessageText); + logger.LogInformation("Notification was successfully processed"); + } + } + catch (Exception ex) + { + logger.LogError(ex, "Exception occurred while processing SNS notification"); + } + return Ok(); + } +} diff --git a/WarehouseApp.FileService/Messaging/SnsSubscriptionService.cs b/WarehouseApp.FileService/Messaging/SnsSubscriptionService.cs new file mode 100644 index 00000000..ac738406 --- /dev/null +++ b/WarehouseApp.FileService/Messaging/SnsSubscriptionService.cs @@ -0,0 +1,43 @@ +using System.Net; +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; + +namespace WarehouseApp.FileService.Messaging; + +/// +/// Служба для подписки на SNS-топик при старте приложения +/// +/// Клиент SNS +/// Конфигурация +/// Логгер +public class SnsSubscriptionService( + IAmazonSimpleNotificationService snsClient, + IConfiguration configuration, + ILogger logger) +{ + private readonly string _topicArn = configuration["AWS:Resources:SNSTopicArn"] + ?? throw new KeyNotFoundException("SNS topic ARN was not found in configuration"); + + /// + /// Подписывает HTTP-эндпоинт текущего сервиса на SNS-топик + /// + public async Task SubscribeEndpoint() + { + logger.LogInformation("Sending subscribe request for {Topic}", _topicArn); + var endpoint = configuration["AWS:Resources:SNSUrl"] + ?? throw new KeyNotFoundException("SNS subscription endpoint URL was not found in configuration"); + + var request = new SubscribeRequest + { + TopicArn = _topicArn, + Protocol = "http", + Endpoint = endpoint, + ReturnSubscriptionArn = true + }; + var response = await snsClient.SubscribeAsync(request); + if (response.HttpStatusCode != HttpStatusCode.OK) + logger.LogError("Failed to subscribe to {Topic}", _topicArn); + else + logger.LogInformation("Subscription request for {Topic} succeeded, waiting for confirmation", _topicArn); + } +} diff --git a/WarehouseApp.FileService/Program.cs b/WarehouseApp.FileService/Program.cs new file mode 100644 index 00000000..17d55d8a --- /dev/null +++ b/WarehouseApp.FileService/Program.cs @@ -0,0 +1,45 @@ +using System.Reflection; +using Amazon.SimpleNotificationService; +using LocalStack.Client.Extensions; +using WarehouseApp.FileService.Messaging; +using WarehouseApp.FileService.Storage; + +var builder = WebApplication.CreateBuilder(args); +builder.AddServiceDefaults(); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(options => +{ + var assembly = Assembly.GetExecutingAssembly(); + var xmlPath = Path.Combine(AppContext.BaseDirectory, $"{assembly.GetName().Name}.xml"); + if (File.Exists(xmlPath)) + options.IncludeXmlComments(xmlPath); +}); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddScoped(); + +builder.AddMinioClient("warehouse-minio"); +builder.Services.AddScoped(); + +var app = builder.Build(); + +using var scope = app.Services.CreateScope(); +var s3Service = scope.ServiceProvider.GetRequiredService(); +await s3Service.EnsureBucketExists(); + +var subscriptionService = scope.ServiceProvider.GetRequiredService(); +await subscriptionService.SubscribeEndpoint(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapDefaultEndpoints(); +app.MapControllers(); + +app.Run(); diff --git a/WarehouseApp.FileService/Properties/launchSettings.json b/WarehouseApp.FileService/Properties/launchSettings.json new file mode 100644 index 00000000..990ac0f0 --- /dev/null +++ b/WarehouseApp.FileService/Properties/launchSettings.json @@ -0,0 +1,40 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:39112", + "sslPort": 44316 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5280", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "launchUrl": "swagger" + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7076;http://localhost:5280", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "launchUrl": "swagger" + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/WarehouseApp.FileService/Storage/IS3Service.cs b/WarehouseApp.FileService/Storage/IS3Service.cs new file mode 100644 index 00000000..12a6e691 --- /dev/null +++ b/WarehouseApp.FileService/Storage/IS3Service.cs @@ -0,0 +1,31 @@ +using System.Text.Json.Nodes; + +namespace WarehouseApp.FileService.Storage; + +/// +/// Служба для манипуляции файлами в объектном хранилище +/// +public interface IS3Service +{ + /// + /// Сохраняет JSON-представление товара в бакет + /// + /// Сериализованный товар в JSON + public Task UploadFile(string fileData); + + /// + /// Возвращает список ключей файлов в бакете + /// + public Task> GetFileList(); + + /// + /// Возвращает JSON-документ по ключу + /// + /// Ключ файла в бакете + public Task DownloadFile(string key); + + /// + /// Создаёт бакет при необходимости + /// + public Task EnsureBucketExists(); +} diff --git a/WarehouseApp.FileService/Storage/S3MinioService.cs b/WarehouseApp.FileService/Storage/S3MinioService.cs new file mode 100644 index 00000000..e119270f --- /dev/null +++ b/WarehouseApp.FileService/Storage/S3MinioService.cs @@ -0,0 +1,132 @@ +using System.Net; +using System.Text; +using System.Text.Json.Nodes; +using Minio; +using Minio.DataModel.Args; + +namespace WarehouseApp.FileService.Storage; + +/// +/// Клиент Minio +/// Конфигурация +/// Логгер +public class S3MinioService( + IMinioClient client, + IConfiguration configuration, + ILogger logger) : IS3Service +{ + 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("Began listing files in {Bucket}", _bucketName); + var responseList = client.ListObjectsEnumAsync(request); + + if (responseList is null) + { + logger.LogWarning("Received null response from {Bucket}", _bucketName); + return list; + } + + 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() + ?? rootNode["Id"]?.GetValue() + ?? throw new ArgumentException("Passed JSON has no 'id' property"); + + var bytes = Encoding.UTF8.GetBytes(fileData); + using var stream = new MemoryStream(bytes); + stream.Seek(0, SeekOrigin.Begin); + + logger.LogInformation("Began uploading warehouse item {Id} into {Bucket}", id, _bucketName); + var request = new PutObjectArgs() + .WithBucket(_bucketName) + .WithStreamData(stream) + .WithObjectSize(bytes.Length) + .WithObject($"warehouse_{id}.json"); + + var response = await client.PutObjectAsync(request); + + if (response.ResponseStatusCode != HttpStatusCode.OK) + { + logger.LogError("Failed to upload warehouse item {Id}: {Code}", id, response.ResponseStatusCode); + return false; + } + logger.LogInformation("Finished uploading warehouse item {Id} to {Bucket}", id, _bucketName); + return true; + } + + /// + public async Task DownloadFile(string key) + { + logger.LogInformation("Began downloading {Key} from {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 is null) + { + logger.LogError("Failed to download {Key}", 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, "Exception occurred during {Key} downloading", key); + throw; + } + } + + /// + public async Task EnsureBucketExists() + { + logger.LogInformation("Checking whether {Bucket} exists", _bucketName); + try + { + var request = new BucketExistsArgs().WithBucket(_bucketName); + var exists = await client.BucketExistsAsync(request); + if (!exists) + { + logger.LogInformation("Creating {Bucket}", _bucketName); + var createRequest = new MakeBucketArgs().WithBucket(_bucketName); + await client.MakeBucketAsync(createRequest); + return; + } + logger.LogInformation("{Bucket} already exists", _bucketName); + } + catch (Exception ex) + { + logger.LogError(ex, "Unhandled exception occurred during {Bucket} check", _bucketName); + throw; + } + } +} diff --git a/WarehouseApp.FileService/WarehouseApp.FileService.csproj b/WarehouseApp.FileService/WarehouseApp.FileService.csproj new file mode 100644 index 00000000..5364d106 --- /dev/null +++ b/WarehouseApp.FileService/WarehouseApp.FileService.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/WarehouseApp.FileService/appsettings.Development.json b/WarehouseApp.FileService/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/WarehouseApp.FileService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/WarehouseApp.FileService/appsettings.json b/WarehouseApp.FileService/appsettings.json new file mode 100644 index 00000000..e3c221f0 --- /dev/null +++ b/WarehouseApp.FileService/appsettings.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "AWS": { + "Resources": { + "LocalStackHost": "localhost", + "LocalStackPort": 4566 + } + } +} diff --git a/WarehouseApp/WarehouseApp.AppHost.Tests/IntegrationTest.cs b/WarehouseApp/WarehouseApp.AppHost.Tests/IntegrationTest.cs new file mode 100644 index 00000000..05c2f89a --- /dev/null +++ b/WarehouseApp/WarehouseApp.AppHost.Tests/IntegrationTest.cs @@ -0,0 +1,131 @@ +using System.Text.Json; +using Aspire.Hosting; +using Microsoft.Extensions.Logging; +using WarehouseApp.Api.Models; + +namespace WarehouseApp.AppHost.Tests; + +/// +/// Интеграционные тесты +/// +public class IntegrationTest : IAsyncLifetime +{ + private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); + + private DistributedApplication? _app; + + /// + public async Task InitializeAsync() + { + var cancellationToken = CancellationToken.None; + IDistributedApplicationTestingBuilder builder = await DistributedApplicationTestingBuilder + .CreateAsync(cancellationToken); + + builder.Configuration["DcpPublisher:RandomizePorts"] = "false"; + + builder.Services.AddLogging(logging => + { + 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); + } + + /// + /// Вызов GET /warehouse-item?id={id} у шлюза кладёт в бакет файл + /// warehouse_{id}.json с тем же содержимым, что и ответ шлюза + /// + [Fact] + public async Task GatewayCall_ProducesFileInS3WithSameId() + { + var cancellationToken = CancellationToken.None; + var id = Random.Shared.Next(1, 1000); + + using var gatewayClient = _app!.CreateHttpClient("api-gateway", "http"); + using var gatewayResponse = await gatewayClient.GetAsync($"/warehouse-item?id={id}", cancellationToken); + gatewayResponse.EnsureSuccessStatusCode(); + + var gatewayItem = JsonSerializer.Deserialize( + await gatewayResponse.Content.ReadAsStringAsync(cancellationToken), + _jsonOptions); + Assert.NotNull(gatewayItem); + + using var sinkClient = _app!.CreateHttpClient("warehouseapp-fileservice", "http"); + + WarehouseItem? s3Item = null; + var deadline = DateTime.UtcNow.AddSeconds(30); + while (DateTime.UtcNow < deadline) + { + using var s3Response = await sinkClient.GetAsync($"/api/s3/warehouse_{id}.json", cancellationToken); + if (s3Response.IsSuccessStatusCode) + { + s3Item = JsonSerializer.Deserialize( + await s3Response.Content.ReadAsStringAsync(cancellationToken), + _jsonOptions); + if (s3Item is not null) + break; + } + await Task.Delay(1000, cancellationToken); + } + + Assert.NotNull(s3Item); + Assert.Equal(id, s3Item!.Id); + Assert.Equivalent(gatewayItem, s3Item); + } + + /// + /// Для нескольких запросов с разными id список ключей бакета содержит + /// отдельный warehouse_{id}.json для каждого id + /// + [Fact] + public async Task MultipleGatewayCalls_ProduceDistinctFilesInS3() + { + var cancellationToken = CancellationToken.None; + var ids = Enumerable.Range(0, 3) + .Select(_ => Random.Shared.Next(1000, 1000000)) + .Distinct() + .ToArray(); + + using var gatewayClient = _app!.CreateHttpClient("api-gateway", "http"); + foreach (var id in ids) + { + using var response = await gatewayClient.GetAsync($"/warehouse-item?id={id}", cancellationToken); + response.EnsureSuccessStatusCode(); + } + + using var sinkClient = _app!.CreateHttpClient("warehouseapp-fileservice", "http"); + var expectedKeys = ids.Select(id => $"warehouse_{id}.json").ToHashSet(); + + HashSet bucketKeys = []; + var deadline = DateTime.UtcNow.AddSeconds(30); + while (DateTime.UtcNow < deadline) + { + using var listResponse = await sinkClient.GetAsync("/api/s3", cancellationToken); + if (listResponse.IsSuccessStatusCode) + { + var keys = JsonSerializer.Deserialize>( + await listResponse.Content.ReadAsStringAsync(cancellationToken), + _jsonOptions); + bucketKeys = keys?.ToHashSet() ?? []; + if (expectedKeys.IsSubsetOf(bucketKeys)) + break; + } + await Task.Delay(1000, cancellationToken); + } + + Assert.Subset(bucketKeys, expectedKeys); + } + + /// + public async Task DisposeAsync() + { + if (_app is not null) + { + await _app.StopAsync(); + await _app.DisposeAsync(); + } + } +} diff --git a/WarehouseApp/WarehouseApp.AppHost.Tests/WarehouseApp.AppHost.Tests.csproj b/WarehouseApp/WarehouseApp.AppHost.Tests/WarehouseApp.AppHost.Tests.csproj new file mode 100644 index 00000000..0575477d --- /dev/null +++ b/WarehouseApp/WarehouseApp.AppHost.Tests/WarehouseApp.AppHost.Tests.csproj @@ -0,0 +1,33 @@ + + + + net8.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WarehouseApp/WarehouseApp.AppHost/AppHost.cs b/WarehouseApp/WarehouseApp.AppHost/AppHost.cs new file mode 100644 index 00000000..9b8cb65e --- /dev/null +++ b/WarehouseApp/WarehouseApp.AppHost/AppHost.cs @@ -0,0 +1,58 @@ +using Amazon; +using Aspire.Hosting.LocalStack.Container; + +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("cache") + .WithRedisCommander(); + +var gateway = builder.AddProject("api-gateway"); + +var awsConfig = builder.AddAWSSDKConfig() + .WithProfile("default") + .WithRegion(RegionEndpoint.EUCentral1); + +var localstack = builder + .AddLocalStack("warehouse-localstack", awsConfig: awsConfig, configureContainer: container => + { + container.Lifetime = ContainerLifetime.Session; + container.DebugLevel = 1; + container.LogLevel = LocalStackLogLevel.Debug; + container.Port = 4566; + container.AdditionalEnvironmentVariables + .Add("DEBUG", "1"); + container.AdditionalEnvironmentVariables + .Add("SNS_CERT_URL_HOST", "sns.eu-central-1.amazonaws.com"); + }); + +var awsResources = builder + .AddAWSCloudFormationTemplate("resources", "CloudFormation/warehouse-template-sns.yaml", "warehouse") + .WithReference(awsConfig); + +var minio = builder.AddMinioContainer("warehouse-minio"); + +for (var i = 0; i < 5; i++) +{ + var api = builder.AddProject($"warehouseapp-api-{i}", launchProfileName: null) + .WithHttpsEndpoint(7250 + i) + .WithReference(cache) + .WithReference(awsResources) + .WaitFor(cache) + .WaitFor(awsResources); + gateway.WaitFor(api); +} + +builder.AddProject("client-wasm") + .WaitFor(gateway); + +builder.AddProject("warehouseapp-fileservice") + .WithReference(awsResources) + .WithReference(minio) + .WithEnvironment("AWS__Resources__SNSUrl", "http://host.docker.internal:5280/api/sns") + .WithEnvironment("AWS__Resources__MinioBucketName", "warehouse-bucket") + .WaitFor(awsResources) + .WaitFor(minio); + +builder.UseLocalStack(localstack); + +builder.Build().Run(); diff --git a/WarehouseApp/WarehouseApp.AppHost/CloudFormation/warehouse-template-sns.yaml b/WarehouseApp/WarehouseApp.AppHost/CloudFormation/warehouse-template-sns.yaml new file mode 100644 index 00000000..08d8139c --- /dev/null +++ b/WarehouseApp/WarehouseApp.AppHost/CloudFormation/warehouse-template-sns.yaml @@ -0,0 +1,29 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: 'Cloud formation template for warehouse project (SNS + Minio variant)' + +Parameters: + TopicName: + Type: String + Description: Name for the SNS topic + Default: 'warehouse-topic' + +Resources: + WarehouseTopic: + Type: AWS::SNS::Topic + Properties: + TopicName: !Ref TopicName + DisplayName: !Ref TopicName + Tags: + - Key: Name + Value: !Ref TopicName + - Key: Environment + Value: Lab3 + +Outputs: + SNSTopicName: + Description: Name of the SNS topic + Value: !GetAtt WarehouseTopic.TopicName + + SNSTopicArn: + Description: ARN of the SNS topic + Value: !Ref WarehouseTopic diff --git a/WarehouseApp/WarehouseApp.AppHost/Properties/launchSettings.json b/WarehouseApp/WarehouseApp.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..ff34ac0e --- /dev/null +++ b/WarehouseApp/WarehouseApp.AppHost/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17181;http://localhost:15266", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21128", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22078" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15266", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19002", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20010" + } + } + } +} diff --git a/WarehouseApp/WarehouseApp.AppHost/WarehouseApp.AppHost.csproj b/WarehouseApp/WarehouseApp.AppHost/WarehouseApp.AppHost.csproj new file mode 100644 index 00000000..b71fb9b4 --- /dev/null +++ b/WarehouseApp/WarehouseApp.AppHost/WarehouseApp.AppHost.csproj @@ -0,0 +1,33 @@ + + + + + + Exe + net8.0 + enable + enable + 18a6328e-1481-4926-bc64-b322ed53ca5c + + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/WarehouseApp/WarehouseApp.AppHost/appsettings.Development.json b/WarehouseApp/WarehouseApp.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/WarehouseApp/WarehouseApp.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/WarehouseApp/WarehouseApp.AppHost/appsettings.json b/WarehouseApp/WarehouseApp.AppHost/appsettings.json new file mode 100644 index 00000000..a6b256bb --- /dev/null +++ b/WarehouseApp/WarehouseApp.AppHost/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "LocalStack": { + "UseLocalStack": true + } +} diff --git a/WarehouseApp/WarehouseApp.ServiceDefaults/Extensions.cs b/WarehouseApp/WarehouseApp.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..b72c8753 --- /dev/null +++ b/WarehouseApp/WarehouseApp.ServiceDefaults/Extensions.cs @@ -0,0 +1,127 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.ServiceDiscovery; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace Microsoft.Extensions.Hosting; + +// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// This project should be referenced by each service project in your solution. +// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults +public static class Extensions +{ + private const string HealthEndpointPath = "/health"; + private const string AlivenessEndpointPath = "/alive"; + + public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.ConfigureOpenTelemetry(); + + builder.AddDefaultHealthChecks(); + + builder.Services.AddServiceDiscovery(); + + builder.Services.ConfigureHttpClientDefaults(http => + { + // Turn on resilience by default + http.AddStandardResilienceHandler(); + + // Turn on service discovery by default + http.AddServiceDiscovery(); + }); + + // Uncomment the following to restrict the allowed schemes for service discovery. + // builder.Services.Configure(options => + // { + // options.AllowedSchemes = ["https"]; + // }); + + return builder; + } + + public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddSource(builder.Environment.ApplicationName) + .AddAspNetCoreInstrumentation(tracing => + // Exclude health check requests from tracing + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) + //.AddGrpcClientInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package) + //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"])) + //{ + // builder.Services.AddOpenTelemetry() + // .UseAzureMonitor(); + //} + + return builder; + } + + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Services.AddHealthChecks() + // Add a default liveness check to ensure app is responsive + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + // Adding health checks endpoints to applications in non-development environments has security implications. + // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments. + if (app.Environment.IsDevelopment()) + { + // All health checks must pass for app to be considered ready to accept traffic after starting + app.MapHealthChecks(HealthEndpointPath); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} diff --git a/WarehouseApp/WarehouseApp.ServiceDefaults/WarehouseApp.ServiceDefaults.csproj b/WarehouseApp/WarehouseApp.ServiceDefaults/WarehouseApp.ServiceDefaults.csproj new file mode 100644 index 00000000..1b6e209a --- /dev/null +++ b/WarehouseApp/WarehouseApp.ServiceDefaults/WarehouseApp.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + +