diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..1c83d9df 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер "№3 "Интеграционное тестирование" + Вариант №16 "Учебный курс" + ВыполнилЧугунов Владислав 6511 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea7..dbbac3ff 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -1,4 +1,4 @@ -{ +{ "$schema": "http://json.schemastore.org/launchsettings.json", "iisSettings": { "windowsAuthentication": false, @@ -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..b954737e 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -1,4 +1,4 @@ -{ +{ "Logging": { "LogLevel": { "Default": "Information", @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7186/courses" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..4d9051f6 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,6 +5,22 @@ 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}") = "TrainingCourseApp.AppHost", "TrainingCourseApp\TrainingCourseApp.AppHost\TrainingCourseApp.AppHost.csproj", "{7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrainingCourseApp.ServiceDefaults", "TrainingCourseApp\TrainingCourseApp.ServiceDefaults\TrainingCourseApp.ServiceDefaults.csproj", "{C53C8EE4-EFE3-1A87-4119-EA1F9BA9141D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrainingCourse.Api", "TrainingCourse.Api\TrainingCourse.Api.csproj", "{91E8399E-D30D-3E51-7F8E-F5AF72E578B5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrainingCourseApp.Gateway", "TrainingCourseApp.Gateway\TrainingCourseApp.Gateway.csproj", "{739465EA-49A5-E75F-FAF6-41307826BFEC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrainingCourseApp.AppHost.Tests", "TrainingCourseApp.AppHost.Tests\TrainingCourseApp.AppHost.Tests.csproj", "{4D19714E-2A07-4BB2-AF50-9ED2BA23E7D6}" + ProjectSection(ProjectDependencies) = postProject + {7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5} = {7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5} + {91E8399E-D30D-3E51-7F8E-F5AF72E578B5} = {91E8399E-D30D-3E51-7F8E-F5AF72E578B5} + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrainingCourseApp.FileService", "TrainingCourseApp.FileService\TrainingCourseApp.FileService.csproj", "{33EF8C66-9FDF-6096-9EB7-0E038C5B8B23}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +31,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 + {7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5}.Release|Any CPU.Build.0 = Release|Any CPU + {C53C8EE4-EFE3-1A87-4119-EA1F9BA9141D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C53C8EE4-EFE3-1A87-4119-EA1F9BA9141D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C53C8EE4-EFE3-1A87-4119-EA1F9BA9141D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C53C8EE4-EFE3-1A87-4119-EA1F9BA9141D}.Release|Any CPU.Build.0 = Release|Any CPU + {91E8399E-D30D-3E51-7F8E-F5AF72E578B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {91E8399E-D30D-3E51-7F8E-F5AF72E578B5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {91E8399E-D30D-3E51-7F8E-F5AF72E578B5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {91E8399E-D30D-3E51-7F8E-F5AF72E578B5}.Release|Any CPU.Build.0 = Release|Any CPU + {739465EA-49A5-E75F-FAF6-41307826BFEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {739465EA-49A5-E75F-FAF6-41307826BFEC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {739465EA-49A5-E75F-FAF6-41307826BFEC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {739465EA-49A5-E75F-FAF6-41307826BFEC}.Release|Any CPU.Build.0 = Release|Any CPU + {4D19714E-2A07-4BB2-AF50-9ED2BA23E7D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4D19714E-2A07-4BB2-AF50-9ED2BA23E7D6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4D19714E-2A07-4BB2-AF50-9ED2BA23E7D6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4D19714E-2A07-4BB2-AF50-9ED2BA23E7D6}.Release|Any CPU.Build.0 = Release|Any CPU + {33EF8C66-9FDF-6096-9EB7-0E038C5B8B23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {33EF8C66-9FDF-6096-9EB7-0E038C5B8B23}.Debug|Any CPU.Build.0 = Debug|Any CPU + {33EF8C66-9FDF-6096-9EB7-0E038C5B8B23}.Release|Any CPU.ActiveCfg = Release|Any CPU + {33EF8C66-9FDF-6096-9EB7-0E038C5B8B23}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Images/AspireAllServices.png b/Images/AspireAllServices.png new file mode 100644 index 00000000..3d3c3b7e Binary files /dev/null and b/Images/AspireAllServices.png differ diff --git a/Images/AspireWork.png b/Images/AspireWork.png new file mode 100644 index 00000000..a20dbaa2 Binary files /dev/null and b/Images/AspireWork.png differ diff --git a/Images/AspireWork_withGateway.png b/Images/AspireWork_withGateway.png new file mode 100644 index 00000000..40357667 Binary files /dev/null and b/Images/AspireWork_withGateway.png differ diff --git a/Images/LogsFileService.png b/Images/LogsFileService.png new file mode 100644 index 00000000..9bc0dcbe Binary files /dev/null and b/Images/LogsFileService.png differ diff --git a/Images/Tests.png b/Images/Tests.png new file mode 100644 index 00000000..9377d235 Binary files /dev/null and b/Images/Tests.png differ diff --git a/Images/WorkApp.png b/Images/WorkApp.png new file mode 100644 index 00000000..25a57d17 Binary files /dev/null and b/Images/WorkApp.png differ diff --git a/Images/WorkBalancer8000.png b/Images/WorkBalancer8000.png new file mode 100644 index 00000000..63844322 Binary files /dev/null and b/Images/WorkBalancer8000.png differ diff --git a/Images/WorkBalancer8001.png b/Images/WorkBalancer8001.png new file mode 100644 index 00000000..ac05287a Binary files /dev/null and b/Images/WorkBalancer8001.png differ diff --git a/Images/WorkBalancer8002.png b/Images/WorkBalancer8002.png new file mode 100644 index 00000000..52cc507c Binary files /dev/null and b/Images/WorkBalancer8002.png differ diff --git "a/Images/WorkCa\321\201he.png" "b/Images/WorkCa\321\201he.png" new file mode 100644 index 00000000..dcab84af Binary files /dev/null and "b/Images/WorkCa\321\201he.png" differ diff --git a/README.md b/README.md index dcaa5eb7..a770a1a9 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,72 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](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). +# Лабораторная работа №2 — «Балансировщик» +## Вариант 16 — «Учебный курс» + +## Описание + +Спроектирован и реализован микросервисный бэкенд для генерации данных учебных курсов. В проекте используется Redis для кэширования запросов, оркестрация микросервисов выполняется средствами .NET Aspire. + +## Реализовано + +- Сервис генерации данных Учебных курсов на основе Bogus +- Кэширование ответов при помощи `IDistributedCache` и Redis +- Структурное логирование сервиса генерации +- Оркестрация всех компонентов через .NET Aspire +- Blazor WebAssembly клиент для отображения данных +- Кастомный балансировщик нагрузки Weighted Round Robin для API Gateway + +## Стек технологий + +- .NET 8 +- .NET Aspire 9.3.1 +- Bogus (v35.6.5) — генерация данных +- Redis (v9.3.1) — распределённое кэширование +- RedisInsight — визуализация данных в Redis +- Blazor WebAssembly — клиентское приложение +- Ocelot — API Gateway + + +## Структура проекта + +| Проект | Описание | +|---|---| +| `TrainingCourse.Api` | API-сервис генерации курсов | +| `TrainingCourse.AppHost` | Aspire-оркестратор | +| `TrainingCourse.ServiceDefaults` | Общие настройки сервисов | +| `Client.Wasm` | Клиент | +| `TrainingCourseApp.Gateway` | API Gateway с кастомным балансировщиком | + +## Характеристики создаваемых курсов + +| № | Название | Тип данных | Источник Bogus | +|---|---|---|---| +| 1 | Идентификатор в системе | int | Параметр запроса | +| 2 | Название курса | string | Company.CatchPhrase() + " course" | +| 3 | ФИО преподавателя | string | Name.FullName() | +| 4 | Дата начала | DateOnly | f.Date.FutureDateOnly(1) | +| 5 | Дата окончания | DateOnly | Date.Between(StartDate, StartDate.AddMonths(6)) | +| 6 | Макс. количество студентов | int | Random.Int(10, 50) | +| 7 | Текущее количество студентов | int | Random.Int(0, MaxStudents) | +| 8 | Наличие сертификата | bool | Random.Bool(0.8f) | +| 9 | Стоимость курса | decimal | Math.Round(Random.Decimal(5000, 50000), 2) | +| 10 | Рейтинг курса | int | Random.Int(1, 5) | + +## Балансировка нагрузки + +Используется балансировщик нагрузки **Weighted Round Robin** для API Gateway, который обеспечивает распределение запросов между несколькими экземплярами сервиса `TrainingCourse.Api` с учётом их весовых коэффициентов. Чем выше вес указан у сервера, тем чаще он будет получаться запросы. + +## Скриншоты + +### Aspire Dashboard +![Aspire Dashboard](Images/AspireWork_withGateway.png) + +### Клиент +![Client](Images/WorkApp.png) + +### Кэширование +![Cache](Images/WorkCaсhe.png) + +### Балансировка +![Balance1](Images/WorkBalancer8000.png) +![Balance1](Images/WorkBalancer8001.png) +![Balance1](Images/WorkBalancer8002.png) diff --git a/TrainingCourse.Api/Messaging/IProducerService.cs b/TrainingCourse.Api/Messaging/IProducerService.cs new file mode 100644 index 00000000..6f148748 --- /dev/null +++ b/TrainingCourse.Api/Messaging/IProducerService.cs @@ -0,0 +1,17 @@ +using TrainingCourse.Api.Models; + +namespace TrainingCourse.Api.Messaging; + +/// +/// Контракт продюсера, отправляющего сгенерированные курсы в брокер сообщений +/// для последующей десериализации файловым сервисом. +/// +public interface IProducerService +{ + /// + /// Сериализует переданный курс в JSON и публикует его в брокер. + /// + /// Сгенерированный курс, который должен быть сохранён в объектное хранилище + /// Задача, завершающаяся после получения подтверждения от брокера + Task SendMessage(Course course); +} diff --git a/TrainingCourse.Api/Messaging/SqsProducerService.cs b/TrainingCourse.Api/Messaging/SqsProducerService.cs new file mode 100644 index 00000000..1953d85f --- /dev/null +++ b/TrainingCourse.Api/Messaging/SqsProducerService.cs @@ -0,0 +1,47 @@ +using System.Net; +using System.Text.Json; +using Amazon.SQS; +using TrainingCourse.Api.Models; + +namespace TrainingCourse.Api.Messaging; + +/// +/// Реализация продюсера поверх AWS SQS. Используется как сервисом генерации, +/// так и через LocalStack — имя/URL очереди берётся из конфигурации +/// (ключ AWS:Resources:SQSQueueName), которую заполняет CloudFormation-стек AppHost. +/// +/// Клиент AWS SQS, сконфигурированный через LocalStack +/// Конфигурация приложения, содержащая адрес очереди +/// Структурный логгер +public class SqsProducerService( + IAmazonSQS client, + IConfiguration configuration, + ILogger logger) : IProducerService +{ + private readonly string _queueName = configuration["AWS:Resources:SQSQueueName"] + ?? throw new KeyNotFoundException("SQS queue name was not found in configuration"); + + private static readonly JsonSerializerOptions SerializerOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + /// + public async Task SendMessage(Course course) + { + try + { + var json = JsonSerializer.Serialize(course, SerializerOptions); + var response = await client.SendMessageAsync(_queueName, json); + + if (response.HttpStatusCode == HttpStatusCode.OK) + logger.LogInformation("Course {CourseId} was sent to file service via SQS", course.Id); + else + throw new Exception($"SQS returned {response.HttpStatusCode}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Unable to send course {CourseId} through SQS queue", course.Id); + } + } +} diff --git a/TrainingCourse.Api/Models/Course.cs b/TrainingCourse.Api/Models/Course.cs new file mode 100644 index 00000000..a877ac3f --- /dev/null +++ b/TrainingCourse.Api/Models/Course.cs @@ -0,0 +1,57 @@ +namespace TrainingCourse.Api.Models; + +/// +/// Модель курса +/// +public class Course +{ + /// + /// Идентификатор в системе + /// + public int Id { get; set; } + + /// + /// Наименование курса + /// + public required string CourseName { get; set; } + + /// + /// ФИО преподавателя + /// + public required string TeacherFullName { get; set; } + + /// + /// Дата начала курса + /// + public required DateOnly StartDate { get; set; } + + /// + /// Дата окончания курса + /// + public required DateOnly EndDate { get; set; } + + /// + /// Максимальное число студентов + /// + public int MaxStudents { get; set; } + + /// + /// Текущее число студентов + /// + public int CurrentStudents { get; set; } + + /// + /// Выдача сертификата по окончании + /// + public bool HasCertificate { get; set; } + + /// + /// Стоимость курса + /// + public decimal Price { get; set; } + + /// + /// Рейтинг курса (1-5) + /// + public int Rating { get; set; } +} \ No newline at end of file diff --git a/TrainingCourse.Api/Program.cs b/TrainingCourse.Api/Program.cs new file mode 100644 index 00000000..9c4cc0ec --- /dev/null +++ b/TrainingCourse.Api/Program.cs @@ -0,0 +1,28 @@ +using Amazon.SQS; +using LocalStack.Client.Extensions; +using TrainingCourse.Api.Messaging; +using TrainingCourse.Api.Services; + + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddScoped(); +builder.Services.AddAwsService(); + +builder.Services.AddScoped(); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +app.MapGet("/api/courses", async (int id, ICourseService courseService) => +{ + var course = await courseService.GetCourse(id); + return Results.Ok(course); +}); + +app.Run(); diff --git a/TrainingCourse.Api/Properties/launchSettings.json b/TrainingCourse.Api/Properties/launchSettings.json new file mode 100644 index 00000000..840df966 --- /dev/null +++ b/TrainingCourse.Api/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:14355", + "sslPort": 44344 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7231;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/TrainingCourse.Api/Services/CourseGenerator.cs b/TrainingCourse.Api/Services/CourseGenerator.cs new file mode 100644 index 00000000..a81b3c19 --- /dev/null +++ b/TrainingCourse.Api/Services/CourseGenerator.cs @@ -0,0 +1,33 @@ +namespace TrainingCourse.Api.Services; + +using Bogus; +using TrainingCourse.Api.Models; + +/// +/// Генератор курсов со случайными свойствами +/// +public static class CourseGenerator +{ + private static readonly Faker _faker = new Faker() + .RuleFor(c => c.CourseName, f => f.Company.CatchPhrase() + " course") + .RuleFor(c => c.TeacherFullName, f => f.Name.FullName()) + .RuleFor(c => c.StartDate, f => f.Date.FutureDateOnly(1)) + .RuleFor(c => c.EndDate, (f, c) => f.Date.BetweenDateOnly(c.StartDate, c.StartDate.AddMonths(6))) + .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(0.8f)) // 80% вероятность выдачи сертификата + .RuleFor(c => c.Price, f => Math.Round(f.Random.Decimal(5000, 50000), 2)) + .RuleFor(c => c.Rating, f => f.Random.Int(1, 5)); + + /// + /// Метод генерации курса + /// + /// Идентификатор курса + /// Курс + public static Course GenerateCourse(int id) + { + var course = _faker.Generate(); + course.Id = id; + return course; + } +} \ No newline at end of file diff --git a/TrainingCourse.Api/Services/CourseService.cs b/TrainingCourse.Api/Services/CourseService.cs new file mode 100644 index 00000000..70045417 --- /dev/null +++ b/TrainingCourse.Api/Services/CourseService.cs @@ -0,0 +1,72 @@ +namespace TrainingCourse.Api.Services; + +using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; +using TrainingCourse.Api.Messaging; +using TrainingCourse.Api.Models; + +/// +/// Прикладной сервис обработки запросов к курсу. +/// Возвращает данные из распределённого кэша, а при их отсутствии генерирует новый курс, +/// публикует его в брокер сообщений (для последующей сериализации в S3) и помещает в кэш. +/// +/// Распределённый кэш Redis, используемый для read-through кэширования +/// Продюсер брокера сообщений, доставляющий курс в файловый сервис +/// Конфигурация приложения (TTL кэша) +/// Структурный логгер +public class CourseService( + IDistributedCache cache, + IProducerService producer, + IConfiguration configuration, + ILogger logger) : ICourseService +{ + private readonly int _expirationMinutes = configuration.GetValue("CacheSettings:ExpirationMinutes", 10); + + /// + public async Task GetCourse(int id) + { + var cacheKey = $"course-{id}"; + logger.LogInformation("Requesting course {CourseId} from cache", id); + var cachedData = await cache.GetStringAsync(cacheKey); + + if (!string.IsNullOrEmpty(cachedData)) + { + try + { + var cachedCourse = JsonSerializer.Deserialize(cachedData); + + if (cachedCourse != null) + { + logger.LogInformation("Course {CourseId} retrieved from cache", id); + return cachedCourse; + } + logger.LogWarning("Course {CourseId} found in cache but deserialization returned null", id); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to deserialize course {CourseId} from cache", id); + } + } + + logger.LogInformation("Course {CourseId} not found in cache. Generating", id); + + var course = CourseGenerator.GenerateCourse(id); + + await producer.SendMessage(course); + + try + { + var cacheOptions = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_expirationMinutes) + }; + await cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(course), cacheOptions); + logger.LogInformation("Course {CourseId} generated and cached", id); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to cache course {CourseId}. Continuing without cache.", id); + } + return course; + } +} diff --git a/TrainingCourse.Api/Services/ICourseService.cs b/TrainingCourse.Api/Services/ICourseService.cs new file mode 100644 index 00000000..f447abdc --- /dev/null +++ b/TrainingCourse.Api/Services/ICourseService.cs @@ -0,0 +1,16 @@ +using TrainingCourse.Api.Models; + +namespace TrainingCourse.Api.Services; + +/// +/// Интерфейс сервиса для работы с курсами +/// +public interface ICourseService +{ + /// + /// Получить курс по идентификатору + /// + /// Идентификатор курса + /// Модель курса + public Task GetCourse(int id); +} \ No newline at end of file diff --git a/TrainingCourse.Api/TrainingCourse.Api.csproj b/TrainingCourse.Api/TrainingCourse.Api.csproj new file mode 100644 index 00000000..bb2158a9 --- /dev/null +++ b/TrainingCourse.Api/TrainingCourse.Api.csproj @@ -0,0 +1,21 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + diff --git a/TrainingCourse.Api/appsettings.Development.json b/TrainingCourse.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/TrainingCourse.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/TrainingCourse.Api/appsettings.json b/TrainingCourse.Api/appsettings.json new file mode 100644 index 00000000..5bfd5d68 --- /dev/null +++ b/TrainingCourse.Api/appsettings.json @@ -0,0 +1,29 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "CacheSettings": { + "ExpirationMinutes": 10 + }, + "Settings": { + "MessageBroker": "SQS" + }, + "LocalStack": { + "UseLocalStack": true, + "Session": { + "RegionName": "eu-central-1", + "AwsAccessKeyId": "test", + "AwsAccessKey": "test" + }, + "Config": { + "LocalStackHost": "localhost", + "EdgePort": 4566, + "UseSsl": false, + "UseLegacyPorts": false + } + } +} diff --git a/TrainingCourseApp.AppHost.Tests/IntegrationTest.cs b/TrainingCourseApp.AppHost.Tests/IntegrationTest.cs new file mode 100644 index 00000000..3f3a85db --- /dev/null +++ b/TrainingCourseApp.AppHost.Tests/IntegrationTest.cs @@ -0,0 +1,192 @@ +using Aspire.Hosting; +using Aspire.Hosting.Testing; +using Microsoft.Extensions.Logging; +using System.Net; +using System.Text.Json; +using TrainingCourse.Api.Models; +using Xunit.Abstractions; + +namespace TrainingCourseApp.AppHost.Tests; + +/// +/// Интеграционные тесты для проверки микросервисного пайплайна: +/// API генерации курсов → SQS (LocalStack) → файловый сервис → MinIO. +/// +/// Служба журналирования юнит-тестов +public class IntegrationTest(ITestOutputHelper output) : IAsyncLifetime +{ + private static readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + private DistributedApplication? _app; + private HttpClient? _gatewayClient; + private HttpClient? _sinkClient; + + /// + 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); + _gatewayClient = _app.CreateHttpClient("trainingcourseapp-gateway", "http"); + _sinkClient = _app.CreateHttpClient("trainingcourseapp-fileservice", "http"); + } + + /// + /// Проверяет, что вызов гейтвея: + /// + /// В ответ отправляет сгенерированный курс + /// Сериализует курс в S3-хранилище + /// Данные из предыдущих пунктов идентичны + /// + /// + [Fact] + public async Task TestPipeline() + { + var random = new Random(); + var id = random.Next(1, 100); + using var gatewayResponse = await _gatewayClient!.GetAsync($"/courses?id={id}"); + var apiCourse = JsonSerializer.Deserialize( + await gatewayResponse.Content.ReadAsStringAsync(), _jsonOptions); + + await Task.Delay(5000); + using var listResponse = await _sinkClient!.GetAsync($"/api/s3"); + var courseList = JsonSerializer.Deserialize>( + await listResponse.Content.ReadAsStringAsync(), _jsonOptions); + using var s3Response = await _sinkClient!.GetAsync($"/api/s3/course_{id}.json"); + var s3Course = JsonSerializer.Deserialize( + await s3Response.Content.ReadAsStringAsync(), _jsonOptions); + + Assert.NotNull(courseList); + Assert.Single(courseList); + Assert.NotNull(apiCourse); + Assert.NotNull(s3Course); + Assert.Equal(id, s3Course.Id); + Assert.Equivalent(apiCourse, s3Course); + } + + /// + /// Проверяет идемпотентность по идентификатору курса: + /// повторный запрос того же id обслуживается из Redis-кэша, + /// продюсер повторно не публикует сообщение, и в бакете остаётся + /// ровно один объект course_{id}.json. + /// + [Fact] + public async Task RepeatedRequestDoesNotDuplicateObjectInBucket() + { + var id = new Random().Next(1, 100); + + using var firstResponse = await _gatewayClient!.GetAsync($"/courses?id={id}"); + var firstCourse = JsonSerializer.Deserialize( + await firstResponse.Content.ReadAsStringAsync(), _jsonOptions); + + using var secondResponse = await _gatewayClient!.GetAsync($"/courses?id={id}"); + var secondCourse = JsonSerializer.Deserialize( + await secondResponse.Content.ReadAsStringAsync(), _jsonOptions); + + await Task.Delay(5000); + + using var listResponse = await _sinkClient!.GetAsync("/api/s3"); + var courseList = JsonSerializer.Deserialize>( + await listResponse.Content.ReadAsStringAsync(), _jsonOptions); + + Assert.NotNull(firstCourse); + Assert.NotNull(secondCourse); + Assert.Equivalent(firstCourse, secondCourse); + Assert.NotNull(courseList); + Assert.Single(courseList); + Assert.Equal($"course_{id}.json", courseList[0]); + } + + /// + /// Проверяет, что пайплайн корректно обрабатывает несколько разных id + /// в рамках одного запуска: каждый сгенерированный курс попадает в бакет + /// под собственным ключом, и содержимое каждого файла совпадает с ответом API. + /// + [Fact] + public async Task MultipleCoursesArePersistedIndependently() + { + var ids = Enumerable.Range(0, 3).Select(i => 200 + i).ToArray(); + + var apiCourses = new Dictionary(); + foreach (var id in ids) + { + using var response = await _gatewayClient!.GetAsync($"/courses?id={id}"); + var course = JsonSerializer.Deserialize( + await response.Content.ReadAsStringAsync(), _jsonOptions); + Assert.NotNull(course); + apiCourses[id] = course!; + } + + await Task.Delay(5000); + + using var listResponse = await _sinkClient!.GetAsync("/api/s3"); + var courseList = JsonSerializer.Deserialize>( + await listResponse.Content.ReadAsStringAsync(), _jsonOptions); + + Assert.NotNull(courseList); + Assert.Equal(ids.Length, courseList.Count); + foreach (var id in ids) + { + Assert.Contains($"course_{id}.json", courseList); + + using var s3Response = await _sinkClient!.GetAsync($"/api/s3/course_{id}.json"); + var s3Course = JsonSerializer.Deserialize( + await s3Response.Content.ReadAsStringAsync(), _jsonOptions); + + Assert.NotNull(s3Course); + Assert.Equivalent(apiCourses[id], s3Course); + } + } + + /// + /// Проверяет, что после round-trip через брокер и объектное хранилище + /// сохранены инварианты доменной модели: рейтинг в диапазоне 1–5, + /// текущее число студентов не превышает максимум, дата окончания не раньше + /// даты начала, обязательные строковые поля не пусты. + /// + [Fact] + public async Task PersistedCourseSatisfiesDomainInvariants() + { + var id = new Random().Next(300, 400); + using var apiResponse = await _gatewayClient!.GetAsync($"/courses?id={id}"); + Assert.Equal(HttpStatusCode.OK, apiResponse.StatusCode); + + await Task.Delay(5000); + + using var s3Response = await _sinkClient!.GetAsync($"/api/s3/course_{id}.json"); + var s3Course = JsonSerializer.Deserialize( + await s3Response.Content.ReadAsStringAsync(), _jsonOptions); + + Assert.NotNull(s3Course); + Assert.Equal(id, s3Course!.Id); + Assert.False(string.IsNullOrWhiteSpace(s3Course.CourseName)); + Assert.False(string.IsNullOrWhiteSpace(s3Course.TeacherFullName)); + Assert.InRange(s3Course.Rating, 1, 5); + Assert.InRange(s3Course.CurrentStudents, 0, s3Course.MaxStudents); + Assert.True(s3Course.EndDate >= s3Course.StartDate); + Assert.True(s3Course.Price > 0); + } + + /// + public async Task DisposeAsync() + { + _gatewayClient?.Dispose(); + _sinkClient?.Dispose(); + await _app!.StopAsync(); + await _app.DisposeAsync(); + } +} diff --git a/TrainingCourseApp.AppHost.Tests/TrainingCourseApp.AppHost.Tests.csproj b/TrainingCourseApp.AppHost.Tests/TrainingCourseApp.AppHost.Tests.csproj new file mode 100644 index 00000000..40824b9b --- /dev/null +++ b/TrainingCourseApp.AppHost.Tests/TrainingCourseApp.AppHost.Tests.csproj @@ -0,0 +1,34 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TrainingCourseApp.FileService/Controllers/S3StorageController.cs b/TrainingCourseApp.FileService/Controllers/S3StorageController.cs new file mode 100644 index 00000000..b2421bea --- /dev/null +++ b/TrainingCourseApp.FileService/Controllers/S3StorageController.cs @@ -0,0 +1,63 @@ +using System.Text; +using System.Text.Json.Nodes; +using Microsoft.AspNetCore.Mvc; +using TrainingCourseApp.FileService.Storage; + +namespace TrainingCourseApp.FileService.Controllers; + +/// +/// HTTP-фасад над объектным хранилищем. Используется в первую очередь +/// интеграционными тестами для верификации того, что курс, сгенерированный API, +/// действительно сохранён в 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} of {Controller} was called", nameof(ListFiles), nameof(S3StorageController)); + 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-документ. + /// + /// Ключ объекта в бакете (например, course_42.json) + [HttpGet("{key}")] + [ProducesResponseType(200)] + [ProducesResponseType(500)] + public async Task> GetFile(string key) + { + logger.LogInformation("{Method} of {Controller} was called for {Key}", nameof(GetFile), nameof(S3StorageController), 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/TrainingCourseApp.FileService/Messaging/SqsConsumerService.cs b/TrainingCourseApp.FileService/Messaging/SqsConsumerService.cs new file mode 100644 index 00000000..d3c37755 --- /dev/null +++ b/TrainingCourseApp.FileService/Messaging/SqsConsumerService.cs @@ -0,0 +1,75 @@ +using Amazon.SQS; +using Amazon.SQS.Model; +using TrainingCourseApp.FileService.Storage; + +namespace TrainingCourseApp.FileService.Messaging; + +/// +/// Фоновая служба, читающая сообщения из SQS батчами, передающая тело сообщения +/// в для сохранения в объектное хранилище и удаляющая +/// успешно обработанные сообщения из очереди. +/// +/// Клиент SQS, сконфигурированный через LocalStack +/// Фабрика DI-скоупов для получения +/// Конфигурация приложения, содержащая URL очереди +/// Структурный логгер +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 consumer service started for queue {Queue}", _queueName); + + while (!stoppingToken.IsCancellationRequested) + { + ReceiveMessageResponse? response; + try + { + response = await sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest + { + QueueUrl = _queueName, + MaxNumberOfMessages = 10, + WaitTimeSeconds = 5 + }, stoppingToken); + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + logger.LogError(ex, "Error while receiving messages from {Queue}", _queueName); + await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken); + continue; + } + + if (response?.Messages == null || response.Messages.Count == 0) + continue; + + logger.LogInformation("Received {Count} messages from {Queue}", response.Messages.Count, _queueName); + + foreach (var message in response.Messages) + { + try + { + using var scope = scopeFactory.CreateScope(); + var s3Service = scope.ServiceProvider.GetRequiredService(); + await s3Service.UploadFile(message.Body); + + await sqsClient.DeleteMessageAsync(_queueName, message.ReceiptHandle, stoppingToken); + } + catch (Exception ex) + { + logger.LogError(ex, "Error processing message: {MessageId}", message.MessageId); + } + } + } + } +} diff --git a/TrainingCourseApp.FileService/Program.cs b/TrainingCourseApp.FileService/Program.cs new file mode 100644 index 00000000..bd9c29d5 --- /dev/null +++ b/TrainingCourseApp.FileService/Program.cs @@ -0,0 +1,47 @@ +using Amazon.SQS; +using LocalStack.Client.Extensions; +using System.Reflection; +using TrainingCourseApp.FileService; +using TrainingCourseApp.FileService.Messaging; +using TrainingCourseApp.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.AddHostedService(); + +builder.AddMinioClient("course-minio"); +builder.Services.AddScoped(); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +using (var scope = app.Services.CreateScope()) +{ + var s3 = scope.ServiceProvider.GetRequiredService(); + await s3.EnsureBucketExists(); +} + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapControllers(); + +app.Run(); diff --git a/TrainingCourseApp.FileService/Properties/launchSettings.json b/TrainingCourseApp.FileService/Properties/launchSettings.json new file mode 100644 index 00000000..6ec4bdb6 --- /dev/null +++ b/TrainingCourseApp.FileService/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:14611", + "sslPort": 44325 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5286", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7117;http://localhost:5286", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/TrainingCourseApp.FileService/Storage/IS3Service.cs b/TrainingCourseApp.FileService/Storage/IS3Service.cs new file mode 100644 index 00000000..92b7fdbe --- /dev/null +++ b/TrainingCourseApp.FileService/Storage/IS3Service.cs @@ -0,0 +1,34 @@ +using System.Text.Json.Nodes; + +namespace TrainingCourseApp.FileService.Storage; + +/// +/// Контракт работы с объектным хранилищем (S3-совместимым) для хранения +/// сериализованных курсов, поступающих из брокера сообщений. +/// +public interface IS3Service +{ + /// + /// Загружает в бакет JSON-представление курса. Имя ключа формируется + /// на основе идентификатора курса вида course_{id}.json. + /// + /// Корректный JSON-документ курса (как в очереди) + /// true, если объект успешно записан + Task UploadFile(string fileData); + + /// + /// Возвращает список ключей всех объектов в управляемом бакете. + /// + Task> GetFileList(); + + /// + /// Скачивает объект по ключу и возвращает его как разобранный JSON-узел. + /// + /// Ключ объекта в бакете + Task DownloadFile(string filePath); + + /// + /// Создаёт бакет, если он отсутствует. Вызывается на старте приложения. + /// + Task EnsureBucketExists(); +} diff --git a/TrainingCourseApp.FileService/Storage/S3MinioService.cs b/TrainingCourseApp.FileService/Storage/S3MinioService.cs new file mode 100644 index 00000000..fae95e99 --- /dev/null +++ b/TrainingCourseApp.FileService/Storage/S3MinioService.cs @@ -0,0 +1,126 @@ +using System.Net; +using System.Text; +using System.Text.Json.Nodes; +using Minio; +using Minio.DataModel.Args; + +namespace TrainingCourseApp.FileService.Storage; + +/// +/// Реализация поверх клиента MinIO. Используется в варианте +/// «SQS + MinIO» лабораторной работы №3. Имя бакета берётся из конфигурации +/// (AWS:Resources:MinioBucketName) и резолвится через Aspire MinIO-ресурс. +/// +/// Низкоуровневый клиент MinIO +/// Конфигурация приложения +/// Структурный логгер +public class S3MinioService( + IMinioClient client, + IConfiguration configuration, + ILogger logger) : IS3Service +{ + private readonly string _bucketName = configuration["AWS:Resources:MinioBucketName"] + ?? throw new KeyNotFoundException("S3 bucket name was not found in configuration"); + + /// + public async Task> GetFileList() + { + var list = new List(); + var request = new ListObjectsArgs() + .WithBucket(_bucketName) + .WithPrefix(string.Empty) + .WithRecursive(true); + + logger.LogInformation("Began listing files in {Bucket}", _bucketName); + var responseList = client.ListObjectsEnumAsync(request); + + 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 no 'id' property"); + + var bytes = Encoding.UTF8.GetBytes(fileData); + using var stream = new MemoryStream(bytes); + + logger.LogInformation("Began uploading course {CourseId} onto {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("Failed to upload course {CourseId}: {StatusCode}", id, response.ResponseStatusCode); + return false; + } + + logger.LogInformation("Finished uploading course {CourseId} to {Bucket}", id, _bucketName); + return true; + } + + /// + public async Task DownloadFile(string filePath) + { + logger.LogInformation("Began downloading {Key} from {Bucket}", filePath, _bucketName); + + try + { + var memoryStream = new MemoryStream(); + var request = new GetObjectArgs() + .WithBucket(_bucketName) + .WithObject(filePath) + .WithCallbackStream(async (stream, ct) => + { + await stream.CopyToAsync(memoryStream, ct); + memoryStream.Seek(0, SeekOrigin.Begin); + }); + + var response = await client.GetObjectAsync(request) + ?? throw new InvalidOperationException($"Empty response for {filePath}"); + + 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", filePath); + throw; + } + } + + /// + public async Task EnsureBucketExists() + { + logger.LogInformation("Checking whether {Bucket} exists", _bucketName); + + try + { + var exists = await client.BucketExistsAsync(new BucketExistsArgs().WithBucket(_bucketName)); + if (exists) + { + logger.LogInformation("{Bucket} already exists", _bucketName); + return; + } + + logger.LogInformation("Creating {Bucket}", _bucketName); + await client.MakeBucketAsync(new MakeBucketArgs().WithBucket(_bucketName)); + } + catch (Exception ex) + { + logger.LogError(ex, "Unhandled exception occurred during {Bucket} check", _bucketName); + throw; + } + } +} diff --git a/TrainingCourseApp.FileService/TrainingCourseApp.FileService.csproj b/TrainingCourseApp.FileService/TrainingCourseApp.FileService.csproj new file mode 100644 index 00000000..1daaca8c --- /dev/null +++ b/TrainingCourseApp.FileService/TrainingCourseApp.FileService.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + true + $(NoWarn);1591 + + + + + + + + + + + + + + + diff --git a/TrainingCourseApp.FileService/appsettings.Development.json b/TrainingCourseApp.FileService/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/TrainingCourseApp.FileService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/TrainingCourseApp.FileService/appsettings.json b/TrainingCourseApp.FileService/appsettings.json new file mode 100644 index 00000000..bbbc54f3 --- /dev/null +++ b/TrainingCourseApp.FileService/appsettings.json @@ -0,0 +1,27 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Settings": { + "MessageBroker": "SQS", + "S3Hosting": "Minio" + }, + "LocalStack": { + "UseLocalStack": true, + "Session": { + "RegionName": "eu-central-1", + "AwsAccessKeyId": "test", + "AwsAccessKey": "test" + }, + "Config": { + "LocalStackHost": "localhost", + "EdgePort": 4566, + "UseSsl": false, + "UseLegacyPorts": false + } + } +} diff --git a/TrainingCourseApp.Gateway/LoadBalancer/WeightedRoundRobinBalancer.cs b/TrainingCourseApp.Gateway/LoadBalancer/WeightedRoundRobinBalancer.cs new file mode 100644 index 00000000..d64b0ff2 --- /dev/null +++ b/TrainingCourseApp.Gateway/LoadBalancer/WeightedRoundRobinBalancer.cs @@ -0,0 +1,88 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace TrainingCourseApp.Gateway.LoadBalancer; + +/// +/// Балансировщик нагрузки, реализующий алгоритм Weighted Round Robin +/// +public class WeightedRoundRobinLoadBalancer : ILoadBalancer +{ + private readonly List _services; + private readonly int[] _weights; // исходные веса + private readonly int[] _currentWeights; // текущие веса для + private readonly int _totalWeight; // сумма всех весов + private readonly object _lock = new(); + + public string Type => nameof(WeightedRoundRobinLoadBalancer).Replace("LoadBalancer", ""); + + public WeightedRoundRobinLoadBalancer(List services, int[]? weights = null) + { + + if (services == null || services.Count == 0) + throw new ArgumentException("Services list cannot be null or empty.", nameof(services)); + + _services = new List(services); + _weights = new int[_services.Count]; + + // Инициализация весов + if (weights != null) + { + for (var i = 0; i < _services.Count && i < weights.Length; i++) + _weights[i] = weights[i]; + for (var i = weights.Length; i < _services.Count; i++) + _weights[i] = 1; + } + else + { + for (var i = 0; i < _services.Count; i++) + { + _weights[i] = i switch + { + 0 => 3, + 1 => 2, + 2 => 1, + _ => 1 + }; + } + } + _totalWeight = _weights.Sum(); + if (_totalWeight <= 0) + throw new InvalidOperationException("Total weight must be greater than zero."); + + _currentWeights = new int[_services.Count]; + Array.Copy(_weights, _currentWeights, _services.Count); + } + + public Task> LeaseAsync(HttpContext context) + { + lock (_lock) + { + var maxIndex = 0; + var maxWeight = _currentWeights[0]; + for (var i = 1; i < _services.Count; i++) + { + if (_currentWeights[i] > maxWeight) + { + maxWeight = _currentWeights[i]; + maxIndex = i; + } + } + _currentWeights[maxIndex] -= _totalWeight; + + for (var i = 0; i < _services.Count; i++) + { + _currentWeights[i] += _weights[i]; + } + + return Task.FromResult>( + new OkResponse(_services[maxIndex])); + } + } + + public void Release(ServiceHostAndPort hostAndPort) + { + + } +} \ No newline at end of file diff --git a/TrainingCourseApp.Gateway/LoadBalancer/WeightedRoundRobinCreator .cs b/TrainingCourseApp.Gateway/LoadBalancer/WeightedRoundRobinCreator .cs new file mode 100644 index 00000000..d316c260 --- /dev/null +++ b/TrainingCourseApp.Gateway/LoadBalancer/WeightedRoundRobinCreator .cs @@ -0,0 +1,74 @@ + +using System.Text.Json; +using Ocelot.Configuration; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.ServiceDiscovery.Providers; + +namespace TrainingCourseApp.Gateway.LoadBalancer; + +/// +/// Создатель балансировщика нагрузки Weighted Round Robin с поддержкой весов из конфигурации +/// +public class WeightedRoundRobinCreator : ILoadBalancerCreator +{ + public string Type => nameof(WeightedRoundRobinCreator).Replace("Creator", ""); + public Response Create( + DownstreamRoute route, + IServiceDiscoveryProvider serviceProvider) + { + var services = serviceProvider.GetAsync().Result; + + var hostAndPorts = services + .Select(s => s.HostAndPort) + .ToList(); + + // Упрощённое чтение весов из ocelot.json (ожидается стандартная структура) + var weights = new List(); + try + { + var configPath = Path.Combine(Directory.GetCurrentDirectory(), "ocelot.json"); + var json = File.ReadAllText(configPath); + using var doc = JsonDocument.Parse(json); + + var routes = doc.RootElement.GetProperty("Routes"); + + foreach (var r in routes.EnumerateArray()) + { + if (r.TryGetProperty("LoadBalancerOptions", out var lb) && + lb.TryGetProperty("Type", out var t) && + string.Equals(t.GetString(), "WeightedRoundRobin", StringComparison.OrdinalIgnoreCase)) + { + var dhps = r.GetProperty("DownstreamHostAndPorts"); + foreach (var hp in dhps.EnumerateArray()) + { + var w = 1; + if (hp.TryGetProperty("Metadata", out var meta) && meta.TryGetProperty("weight", out var wEl)) + { + if (wEl.ValueKind == JsonValueKind.String) + int.TryParse(wEl.GetString(), out w); + else if (wEl.ValueKind == JsonValueKind.Number) + wEl.TryGetInt32(out w); + } + + if (w <= 0) w = 1; + weights.Add(w); + } + + break; // нашли нужный маршрут — выходим + } + } + } + catch + { + // при любой ошибке используем веса по умолчанию + } + + if (weights.Count == 0) + weights = Enumerable.Repeat(1, hostAndPorts.Count).ToList(); + + var balancer = new WeightedRoundRobinLoadBalancer(hostAndPorts, weights.ToArray()); + + return new OkResponse(balancer); + } +} \ No newline at end of file diff --git a/TrainingCourseApp.Gateway/Program.cs b/TrainingCourseApp.Gateway/Program.cs new file mode 100644 index 00000000..b951fda9 --- /dev/null +++ b/TrainingCourseApp.Gateway/Program.cs @@ -0,0 +1,96 @@ +using System.Text.Json.Nodes; +using Ocelot.DependencyInjection; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Middleware; +using TrainingCourseApp.Gateway.LoadBalancer; + +var builder = WebApplication.CreateBuilder(args); + +// If environment variable DOWNSTREAM_HOSTS is provided, rebuild DownstreamHostAndPorts in ocelot.json +// Expected format: comma-separated entries: "host:port:weight" or "host:port" (weight defaults to 1) +try +{ + var env = Environment.GetEnvironmentVariable("DOWNSTREAM_HOSTS"); + if (!string.IsNullOrWhiteSpace(env)) + { + var configPath = Path.Combine(Directory.GetCurrentDirectory(), "ocelot.json"); + if (File.Exists(configPath)) + { + var json = File.ReadAllText(configPath); + var root = JsonNode.Parse(json); + var routes = root?["Routes"] as JsonArray; + if (root != null && routes != null) + { + // parse env into host entries + var entries = env.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var downstreamArray = new JsonArray(); + foreach (var e in entries) + { + // host:port[:weight] + var parts = e.Split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (parts.Length >= 2) + { + var host = parts[0]; + if (!int.TryParse(parts[1], out var port)) + continue; + var weight = 1; + if (parts.Length >= 3) + int.TryParse(parts[2], out weight); + + var obj = new JsonObject + { + ["Host"] = host, + ["Port"] = port, + ["Metadata"] = new JsonObject { ["weight"] = weight.ToString() } + }; + + downstreamArray.Add(obj); + } + } + + if (downstreamArray.Count > 0) + { + // Replace DownstreamHostAndPorts for routes that specify WeightedRoundRobin + foreach (var r in routes) + { + if (r is null) continue; + var lb = r["LoadBalancerOptions"] as JsonObject; + if (lb != null && string.Equals(lb["Type"]?.ToString(), "WeightedRoundRobin", StringComparison.OrdinalIgnoreCase)) + { + r["DownstreamHostAndPorts"] = downstreamArray; + } + } + + // write back file + File.WriteAllText(configPath, root.ToJsonString(new System.Text.Json.JsonSerializerOptions { WriteIndented = true })); + } + } + } + } +} +catch +{ + // ignore any errors and fall back to existing config +} + +builder.AddServiceDefaults(); +builder.Services.AddServiceDiscovery(); +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); + +builder.Services.AddCors(options => + options.AddPolicy("AllowClient", policy => + policy.WithOrigins(builder.Configuration.GetSection("CorsSettings:AllowedOrigins").Get() ?? []) + .WithMethods("GET") + .AllowAnyHeader())); + +builder.Services.AddOcelot(); +builder.Services.AddSingleton(); + +var app = builder.Build(); + +app.UseCors("AllowClient"); +app.MapDefaultEndpoints(); + +await app.UseOcelot(); + +app.Run(); \ No newline at end of file diff --git a/TrainingCourseApp.Gateway/Properties/launchSettings.json b/TrainingCourseApp.Gateway/Properties/launchSettings.json new file mode 100644 index 00000000..d15f6f70 --- /dev/null +++ b/TrainingCourseApp.Gateway/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:59078", + "sslPort": 44344 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5224", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7186;http://localhost:5224", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/TrainingCourseApp.Gateway/TrainingCourseApp.Gateway.csproj b/TrainingCourseApp.Gateway/TrainingCourseApp.Gateway.csproj new file mode 100644 index 00000000..0b258968 --- /dev/null +++ b/TrainingCourseApp.Gateway/TrainingCourseApp.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/TrainingCourseApp.Gateway/appsettings.Development.json b/TrainingCourseApp.Gateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/TrainingCourseApp.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/TrainingCourseApp.Gateway/appsettings.json b/TrainingCourseApp.Gateway/appsettings.json new file mode 100644 index 00000000..525d3559 --- /dev/null +++ b/TrainingCourseApp.Gateway/appsettings.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "CorsSettings": { + "AllowedOrigins": [ + "http://localhost:5127", + "https://localhost:7282" + ] + } +} diff --git a/TrainingCourseApp.Gateway/ocelot.json b/TrainingCourseApp.Gateway/ocelot.json new file mode 100644 index 00000000..96b53b78 --- /dev/null +++ b/TrainingCourseApp.Gateway/ocelot.json @@ -0,0 +1,38 @@ +{ + "Routes": [ + { + "UpstreamPathTemplate": "/courses", + "UpstreamHttpMethod": [ + "GET" + ], + "DownstreamPathTemplate": "/api/courses", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 5500, + "Metadata": { + "weight": "3" + } + }, + { + "Host": "localhost", + "Port": 5501, + "Metadata": { + "weight": "2" + } + }, + { + "Host": "localhost", + "Port": 5502, + "Metadata": { + "weight": "1" + } + } + ], + "LoadBalancerOptions": { + "Type": "WeightedRoundRobin" + } + } + ] +} \ No newline at end of file diff --git a/TrainingCourseApp/TrainingCourseApp.AppHost/AppHost.cs b/TrainingCourseApp/TrainingCourseApp.AppHost/AppHost.cs new file mode 100644 index 00000000..0638b7bd --- /dev/null +++ b/TrainingCourseApp/TrainingCourseApp.AppHost/AppHost.cs @@ -0,0 +1,78 @@ +using Amazon; +using Aspire.Hosting.LocalStack.Container; + +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisInsight(); + +var awsConfig = builder.AddAWSSDKConfig() + .WithProfile("default") + .WithRegion(RegionEndpoint.EUCentral1); + +var localstack = builder + .AddLocalStack("course-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-sqs.yaml", "course") + .WithReference(awsConfig); + +var minio = builder.AddMinioContainer("course-minio"); + +var gateway = builder.AddProject("trainingcourseapp-gateway"); + +var apiPorts = new List(); +for (var i = 0; i < 3; i++) +{ + var port = 5500 + i; + apiPorts.Add(port); + + var service = builder.AddProject($"trainingcourseapp-api-{i}", launchProfileName: null) + .WithHttpsEndpoint(port) + .WithReference(redis) + .WithReference(awsResources) + .WithEnvironment("Settings__MessageBroker", "SQS") + .WaitFor(redis) + .WaitFor(awsResources); + + gateway.WithReference(service); + gateway.WaitFor(service); +} + +try +{ + var entries = new List(); + for (var i = 0; i < apiPorts.Count; i++) + { + var weight = i == 0 ? 3 : i == 1 ? 2 : 1; + entries.Add($"localhost:{apiPorts[i]}:{weight}"); + } + Environment.SetEnvironmentVariable("DOWNSTREAM_HOSTS", string.Join(',', entries)); +} +catch +{ + // ignore +} + +var fileService = builder.AddProject("trainingcourseapp-fileservice") + .WithReference(awsResources) + .WithReference(minio) + .WithEnvironment("Settings__MessageBroker", "SQS") + .WithEnvironment("Settings__S3Hosting", "Minio") + .WithEnvironment("AWS__Resources__MinioBucketName", "course-bucket") + .WaitFor(awsResources) + .WaitFor(minio); + +builder.AddProject("client-wasm") + .WaitFor(gateway); + +builder.UseLocalStack(localstack); + +builder.Build().Run(); diff --git a/TrainingCourseApp/TrainingCourseApp.AppHost/CloudFormation/course-template-sqs.yaml b/TrainingCourseApp/TrainingCourseApp.AppHost/CloudFormation/course-template-sqs.yaml new file mode 100644 index 00000000..d62ac47d --- /dev/null +++ b/TrainingCourseApp/TrainingCourseApp.AppHost/CloudFormation/course-template-sqs.yaml @@ -0,0 +1,32 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: 'Cloud formation template for training course project (variant: SQS + MinIO)' + +Parameters: + QueueName: + Type: String + Description: Name for the SQS queue used to deliver generated courses to the file service + 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: Lab3 + +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/TrainingCourseApp/TrainingCourseApp.AppHost/Properties/launchSettings.json b/TrainingCourseApp/TrainingCourseApp.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..1d2a541d --- /dev/null +++ b/TrainingCourseApp/TrainingCourseApp.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:17086;http://localhost:15193", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21146", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22096" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15193", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19210", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20142" + } + } + } +} \ No newline at end of file diff --git a/TrainingCourseApp/TrainingCourseApp.AppHost/TrainingCourseApp.AppHost.csproj b/TrainingCourseApp/TrainingCourseApp.AppHost/TrainingCourseApp.AppHost.csproj new file mode 100644 index 00000000..5f6972dd --- /dev/null +++ b/TrainingCourseApp/TrainingCourseApp.AppHost/TrainingCourseApp.AppHost.csproj @@ -0,0 +1,32 @@ + + + + + + Exe + net8.0 + enable + enable + 58fecc7f-bf3d-43e2-867c-8457c65da978 + + + + + + + + + + + + + + + + + + + Always + + + diff --git a/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.Development.json b/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.json b/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.json new file mode 100644 index 00000000..c3862417 --- /dev/null +++ b/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "LocalStack": { + "UseLocalStack": true + } +} diff --git a/TrainingCourseApp/TrainingCourseApp.ServiceDefaults/Extensions.cs b/TrainingCourseApp/TrainingCourseApp.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..112c1281 --- /dev/null +++ b/TrainingCourseApp/TrainingCourseApp.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 .NET Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// This project should be referenced by each service project in your solution. +// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults +public static class Extensions +{ + 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/TrainingCourseApp/TrainingCourseApp.ServiceDefaults/TrainingCourseApp.ServiceDefaults.csproj b/TrainingCourseApp/TrainingCourseApp.ServiceDefaults/TrainingCourseApp.ServiceDefaults.csproj new file mode 100644 index 00000000..d808731c --- /dev/null +++ b/TrainingCourseApp/TrainingCourseApp.ServiceDefaults/TrainingCourseApp.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + +