diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..87b38c08 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №3 "Интеграционное тестирование" + Вариант №47 "Транспортное средство" + Выполнена Морозов Сергей Сергеевич 6513 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea7..60120ec3 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -12,7 +12,7 @@ "http": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "http://localhost:5127", "environmentVariables": { @@ -22,7 +22,7 @@ "https": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "https://localhost:7282;http://localhost:5127", "environmentVariables": { @@ -31,7 +31,7 @@ }, "IIS Express": { "commandName": "IISExpress", - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..765ff8a3 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7163/vehicles" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..0d6971ed 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}") = "VehicleApp.AppHost", "VehicleApp\VehicleApp.AppHost\VehicleApp.AppHost.csproj", "{5A32E624-1368-47E1-AE8C-C5D666C99826}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleApp.ServiceDefaults", "VehicleApp\VehicleApp.ServiceDefaults\VehicleApp.ServiceDefaults.csproj", "{97B1F7F0-C53D-2D4D-3803-B1150F873870}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleApp.Api", "VehicleApp.Api\VehicleApp.Api.csproj", "{54C02CF3-616B-EC3E-6F35-EAF0ED92B6B0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleApp.Gateway", "VehicleApp.Gateway\VehicleApp.Gateway.csproj", "{CBFDC59A-3449-C88A-3139-3F56883062A4}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleApp.AppHost.Tests", "VehicleApp.AppHost.Tests\VehicleApp.AppHost.Tests.csproj", "{D88DD2ED-1E2A-4997-80D5-BE76658A927B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "File.Service", "File.Service\File.Service.csproj", "{DF944664-05C9-E01F-B262-C8B381C1EFE1}" +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 + {5A32E624-1368-47E1-AE8C-C5D666C99826}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5A32E624-1368-47E1-AE8C-C5D666C99826}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5A32E624-1368-47E1-AE8C-C5D666C99826}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5A32E624-1368-47E1-AE8C-C5D666C99826}.Release|Any CPU.Build.0 = Release|Any CPU + {97B1F7F0-C53D-2D4D-3803-B1150F873870}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {97B1F7F0-C53D-2D4D-3803-B1150F873870}.Debug|Any CPU.Build.0 = Debug|Any CPU + {97B1F7F0-C53D-2D4D-3803-B1150F873870}.Release|Any CPU.ActiveCfg = Release|Any CPU + {97B1F7F0-C53D-2D4D-3803-B1150F873870}.Release|Any CPU.Build.0 = Release|Any CPU + {54C02CF3-616B-EC3E-6F35-EAF0ED92B6B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {54C02CF3-616B-EC3E-6F35-EAF0ED92B6B0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {54C02CF3-616B-EC3E-6F35-EAF0ED92B6B0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {54C02CF3-616B-EC3E-6F35-EAF0ED92B6B0}.Release|Any CPU.Build.0 = Release|Any CPU + {CBFDC59A-3449-C88A-3139-3F56883062A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CBFDC59A-3449-C88A-3139-3F56883062A4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CBFDC59A-3449-C88A-3139-3F56883062A4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CBFDC59A-3449-C88A-3139-3F56883062A4}.Release|Any CPU.Build.0 = Release|Any CPU + {D88DD2ED-1E2A-4997-80D5-BE76658A927B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D88DD2ED-1E2A-4997-80D5-BE76658A927B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D88DD2ED-1E2A-4997-80D5-BE76658A927B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D88DD2ED-1E2A-4997-80D5-BE76658A927B}.Release|Any CPU.Build.0 = Release|Any CPU + {DF944664-05C9-E01F-B262-C8B381C1EFE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DF944664-05C9-E01F-B262-C8B381C1EFE1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DF944664-05C9-E01F-B262-C8B381C1EFE1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF944664-05C9-E01F-B262-C8B381C1EFE1}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/File.Service/Controllers/S3Controller.cs b/File.Service/Controllers/S3Controller.cs new file mode 100644 index 00000000..3ae5e61b --- /dev/null +++ b/File.Service/Controllers/S3Controller.cs @@ -0,0 +1,47 @@ +using System.Text.Json.Nodes; +using File.Service.Storage; +using Microsoft.AspNetCore.Mvc; + +namespace File.Service.Controllers; + +/// +/// HTTP-интерфейс на чтение содержимого бакета Minio. +/// Используется интеграционными тестами и для ручной проверки состояния хранилища +/// +/// Сервис доступа к бакету +/// Логгер HTTP-обращений +[ApiController] +[Route("api/s3")] +public class S3Controller(IS3Service s3Service, ILogger logger) : ControllerBase +{ + /// + /// Возвращает список ключей всех объектов в бакете + /// + [HttpGet] + public async Task>> ListFiles() + { + logger.LogInformation("ListFiles was called"); + var list = await s3Service.GetFileList(); + return Ok(list); + } + + /// + /// Возвращает содержимое объекта по ключу. Если объекта нет — 404 + /// + /// Ключ объекта в бакете, например vehicle_42.json + [HttpGet("{key}")] + public async Task> GetFile(string key) + { + logger.LogInformation("GetFile was called for {key}", key); + try + { + var node = await s3Service.DownloadFile(key); + return Ok(node); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to download {key}", key); + return NotFound(); + } + } +} diff --git a/File.Service/Controllers/SnsWebhookController.cs b/File.Service/Controllers/SnsWebhookController.cs new file mode 100644 index 00000000..1ffc78ad --- /dev/null +++ b/File.Service/Controllers/SnsWebhookController.cs @@ -0,0 +1,69 @@ +using System.Text; +using Amazon.SimpleNotificationService.Util; +using File.Service.Storage; +using Microsoft.AspNetCore.Mvc; + +namespace File.Service.Controllers; + +/// +/// Эндпоинт, на который SNS отправляет запросы подтверждения подписки и уведомления +/// +/// Сервис записи в Minio +/// Логгер входящих сообщений +[ApiController] +[Route("api/sns")] +public class SnsWebhookController(IS3Service s3Service, ILogger logger) : ControllerBase +{ + /// + /// Обрабатывает тело SNS-запроса. Для SubscriptionConfirmation выполняет GET + /// по SubscribeURL (с переписыванием адреса на LocalStack). Для Notification + /// передаёт сообщение в . Всегда отвечает 200, + /// чтобы SNS не помечал подписчика как недоступного + /// + [HttpPost] + public async Task ReceiveMessage() + { + logger.LogInformation("SNS webhook was called"); + using var reader = new StreamReader(Request.Body, Encoding.UTF8); + var body = await reader.ReadToEndAsync(); + + try + { + var message = Message.ParseMessage(body); + + if (message.Type == "SubscriptionConfirmation") + { + logger.LogInformation("Received SubscriptionConfirmation, confirming"); + using var http = new HttpClient(); + var builder = new UriBuilder(new Uri(message.SubscribeURL)) + { + Scheme = "http", + Host = "localhost", + Port = 4566 + }; + var confirmation = await http.GetAsync(builder.Uri); + if (!confirmation.IsSuccessStatusCode) + { + var text = await confirmation.Content.ReadAsStringAsync(); + logger.LogError("SubscriptionConfirmation returned {code}: {body}", confirmation.StatusCode, text); + } + else + { + logger.LogInformation("Subscription confirmed"); + } + return Ok(); + } + + if (message.Type == "Notification") + { + await s3Service.UploadFile(message.MessageText); + logger.LogInformation("Notification was processed and uploaded to Minio"); + } + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to process SNS message"); + } + return Ok(); + } +} diff --git a/File.Service/File.Service.csproj b/File.Service/File.Service.csproj new file mode 100644 index 00000000..96aa422e --- /dev/null +++ b/File.Service/File.Service.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + true + $(NoWarn);1591 + + + + + + + + + + + + + + + diff --git a/File.Service/Messaging/SnsSubscriptionService.cs b/File.Service/Messaging/SnsSubscriptionService.cs new file mode 100644 index 00000000..2c9326e2 --- /dev/null +++ b/File.Service/Messaging/SnsSubscriptionService.cs @@ -0,0 +1,43 @@ +using System.Net; +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; + +namespace File.Service.Messaging; + +/// +/// На старте приложения регистрирует HTTP-вебхук File.Service в SNS-топике +/// +/// SNS-клиент для вызова Subscribe +/// Источник ARN топика и URL подписчика +/// Логгер +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"); + private readonly string _endpoint = configuration["AWS:Resources:SNSUrl"] + ?? throw new KeyNotFoundException("SNS subscriber endpoint was not found in configuration"); + + /// + /// Отправляет в SNS запрос Subscribe. Подтверждение подписки + /// выполняется позже в + /// + public async Task SubscribeEndpoint() + { + logger.LogInformation("Subscribing endpoint {endpoint} to topic {topic}", _endpoint, _topicArn); + 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}: {code}", _topicArn, response.HttpStatusCode); + else + logger.LogInformation("Subscription request for {topic} accepted; awaiting confirmation", _topicArn); + } +} diff --git a/File.Service/Program.cs b/File.Service/Program.cs new file mode 100644 index 00000000..841e64ca --- /dev/null +++ b/File.Service/Program.cs @@ -0,0 +1,44 @@ +using Amazon.SimpleNotificationService; +using File.Service.Messaging; +using File.Service.Storage; +using LocalStack.Client.Extensions; +using System.Reflection; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.Services.AddSwaggerGen(options => +{ + var assembly = Assembly.GetExecutingAssembly(); + options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{assembly.GetName().Name}.xml")); +}); + +builder.Services.AddControllers(); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddScoped(); + +builder.AddMinioClient("vehicle-minio"); +builder.Services.AddScoped(); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapDefaultEndpoints(); + +using var scope = app.Services.CreateScope(); + +var s3 = scope.ServiceProvider.GetRequiredService(); +await s3.EnsureBucketExists(); +var subscription = scope.ServiceProvider.GetRequiredService(); +await subscription.SubscribeEndpoint(); + + +app.MapControllers(); +app.Run(); diff --git a/File.Service/Properties/launchSettings.json b/File.Service/Properties/launchSettings.json new file mode 100644 index 00000000..aa554908 --- /dev/null +++ b/File.Service/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "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:7017;http://localhost:5280", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "launchUrl": "swagger" + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/File.Service/Storage/IS3Service.cs b/File.Service/Storage/IS3Service.cs new file mode 100644 index 00000000..ec4d4f32 --- /dev/null +++ b/File.Service/Storage/IS3Service.cs @@ -0,0 +1,32 @@ +using System.Text.Json.Nodes; + +namespace File.Service.Storage; + +/// +/// Сервис работы с Minio-бакетом, в который сохраняются ТС из SNS-уведомлений +/// +public interface IS3Service +{ + /// + /// Создаёт бакет, если его ещё нет + /// + Task EnsureBucketExists(); + + /// + /// Сохраняет JSON-тело SNS-сообщения в бакет под ключом vehicle_{id}.json + /// + /// Сериализованное ТС + /// true при успешной загрузке + Task UploadFile(string fileData); + + /// + /// Возвращает список ключей всех объектов в бакете + /// + Task> GetFileList(); + + /// + /// Читает объект из бакета и парсит его как JSON + /// + /// Ключ объекта + Task DownloadFile(string key); +} diff --git a/File.Service/Storage/MinioS3Service.cs b/File.Service/Storage/MinioS3Service.cs new file mode 100644 index 00000000..af648cbf --- /dev/null +++ b/File.Service/Storage/MinioS3Service.cs @@ -0,0 +1,93 @@ +using System.Net; +using System.Text; +using System.Text.Json.Nodes; +using Minio; +using Minio.DataModel.Args; + +namespace File.Service.Storage; + +/// +/// Реализация на клиенте Minio. +/// Имя бакета берётся из ключа AWS:Resources:MinioBucketName +/// +/// Клиент Minio +/// Источник имени бакета +/// Логгер операций с бакетом +public class MinioS3Service(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 EnsureBucketExists() + { + logger.LogInformation("Checking whether bucket {bucket} exists", _bucketName); + var exists = await client.BucketExistsAsync(new BucketExistsArgs().WithBucket(_bucketName)); + if (exists) + { + logger.LogInformation("Bucket {bucket} already exists", _bucketName); + return; + } + logger.LogInformation("Creating bucket {bucket}", _bucketName); + await client.MakeBucketAsync(new MakeBucketArgs().WithBucket(_bucketName)); + } + + /// + public async Task UploadFile(string fileData) + { + var root = JsonNode.Parse(fileData) ?? throw new ArgumentException("Passed string is not a valid JSON"); + var id = root["Id"]?.GetValue() + ?? root["id"]?.GetValue() + ?? throw new ArgumentException("Passed JSON has no 'Id' property"); + + var key = $"vehicle_{id}.json"; + var bytes = Encoding.UTF8.GetBytes(fileData); + using var stream = new MemoryStream(bytes); + + logger.LogInformation("Uploading {key} to bucket {bucket}", key, _bucketName); + var request = new PutObjectArgs() + .WithBucket(_bucketName) + .WithObject(key) + .WithStreamData(stream) + .WithObjectSize(bytes.Length); + var response = await client.PutObjectAsync(request); + + if (response.ResponseStatusCode != HttpStatusCode.OK) + { + logger.LogError("Failed to upload {key}: status {code}", key, response.ResponseStatusCode); + return false; + } + logger.LogInformation("Successfully uploaded {key}", key); + return true; + } + + /// + public async Task> GetFileList() + { + var keys = new List(); + var request = new ListObjectsArgs().WithBucket(_bucketName).WithRecursive(true); + logger.LogInformation("Listing objects in bucket {bucket}", _bucketName); + await foreach (var item in client.ListObjectsEnumAsync(request)) + keys.Add(item.Key); + return keys; + } + + /// + public async Task DownloadFile(string key) + { + logger.LogInformation("Downloading {key} from bucket {bucket}", key, _bucketName); + var memory = new MemoryStream(); + var request = new GetObjectArgs() + .WithBucket(_bucketName) + .WithObject(key) + .WithCallbackStream(async (s, ct) => + { + await s.CopyToAsync(memory, ct); + memory.Seek(0, SeekOrigin.Begin); + }); + await client.GetObjectAsync(request); + using var reader = new StreamReader(memory, Encoding.UTF8); + return JsonNode.Parse(reader.ReadToEnd()) + ?? throw new InvalidOperationException($"Downloaded {key} is not a valid JSON"); + } +} diff --git a/File.Service/appsettings.Development.json b/File.Service/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/File.Service/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/File.Service/appsettings.json b/File.Service/appsettings.json new file mode 100644 index 00000000..a3c034a8 --- /dev/null +++ b/File.Service/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "LocalStack": { + "UseLocalStack": true + } +} diff --git a/README.md b/README.md index dcaa5eb7..843e87eb 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,110 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](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). +# Лабораторные работы — «Облачная разработка» +## Вариант 47 — «Транспортное средство» + +--- + +## Лабораторная работа №1 — «Кэширование» + +### Описание + +Реализован микросервисный бэкенд для генерации данных о транспортных средствах с кэшированием в Redis и оркестрацией через .NET Aspire. + +### Что реализовано + +- Сервис генерации данных о транспортных средствах на основе Bogus +- Кэширование ответов при помощи `IDistributedCache` и Redis +- Структурное логирование сервиса генерации +- Оркестрация всех компонентов через .NET Aspire +- Blazor WebAssembly клиент для отображения данных + +--- + +## Лабораторная работа №2 — «Балансировка нагрузки» + +### Описание + +Реализован API Gateway на основе Ocelot с кастомным алгоритмом балансировки нагрузки **Query Based**. + +### Что реализовано + +- Запуск 7 реплик сервиса генерации через .NET Aspire (порты 5000–5006) +- API Gateway на Ocelot с маршрутизацией `/vehicles` → `/api/vehicles` +- Кастомный балансировщик `QueryBased` — реплика выбирается по формуле `id % N`, где N — число реплик + +### Алгоритм балансировки + +Из query-параметра `id` вычисляется остаток от деления на количество реплик. Результат — индекс реплики, обрабатывающей запрос. + +--- + +## Лабораторная работа №3 — «Брокер сообщений и объектное хранилище» + +### Описание + +Расширен пайплайн генерации ТС: после генерации нового ТС сервис публикует его в брокер сообщений, отдельный файловый сервис забирает сообщение и кладёт JSON в объектное хранилище. + +Вариант **47** — **SNS + Minio**: брокер сообщений AWS SNS (эмулируется через LocalStack), хранилище — Minio с S3-совместимым API. + +### Что реализовано + +- **`VehicleApp.Api`** — при генерации нового ТС публикует JSON в SNS-топик (`SnsVehiclePublisher`). Если ТС взято из Redis — публикации нет. +- **`File.Service`** — новый сервис: + - `SnsSubscriptionService` подписывает эндпоинт `http://host.docker.internal:5280/api/sns` на SNS-топик при старте; + - `SnsWebhookController` принимает `SubscriptionConfirmation` и `Notification`; + - `MinioS3Service` создаёт бакет `vehicle-bucket` и складывает ТС под ключом `vehicle_{id}.json`; + - `S3Controller` отдаёт список ключей (`GET /api/s3`) и содержимое файла (`GET /api/s3/{key}`). +- **`VehicleApp.AppHost`** — добавлены контейнеры LocalStack (SNS, порт 4566) и Minio, CloudFormation-шаблон `CloudFormation/vehicle-sns.yaml` создаёт SNS-топик `vehicle-topic`, ARN пробрасывается в реплики API и в File.Service через `AWS:Resources:SNSTopicArn`. +- **`VehicleApp.AppHost.Tests`** — интеграционный тест `GatewayRequest_PublishesVehicleToMinio`: стучится в **гейтвей** с конкретным `id`, затем поллит `/api/s3/vehicle_{id}.json` в File.Service и сверяет содержимое с ответом гейтвея. + +### Стек технологий (дополнение) + +- LocalStack 2.x (эмуляция AWS SNS) +- AWSSDK.SimpleNotificationService +- Minio (.NET клиент `CommunityToolkit.Aspire.Minio.Client`) +- Aspire.Hosting CloudFormation (создание SNS-топика) + +## Стек технологий + +- .NET 8 +- .NET Aspire 9.5 +- Bogus — генерация данных +- Redis — распределённое кэширование +- RedisInsight — визуализация данных в Redis +- Blazor WebAssembly — клиентское приложение +- OpenTelemetry — метрики, трейсинг, логирование + +## Структура проекта + +| Проект | Описание | +|---|---| +| `VehicleApp.Api` | API-сервис генерации транспортных средств (7 реплик), публикует ТС в SNS | +| `VehicleApp.Gateway` | API Gateway на Ocelot с балансировкой Query Based | +| `File.Service` | Подписчик SNS, сохраняет JSON в Minio | +| `VehicleApp.AppHost` | Aspire-оркестратор (Redis + LocalStack + Minio + сервисы) | +| `VehicleApp.AppHost.Tests` | Интеграционные тесты пайплайна | +| `VehicleApp.ServiceDefaults` | Общие настройки сервисов (OpenTelemetry, health checks) | +| `Client.Wasm` | Blazor WebAssembly клиент | + +## Характеристики транспортного средства + +| № | Название | Тип данных | Источник Bogus | +|---|---|---|---| +| 1 | Идентификатор в системе | `int` | Параметр запроса | +| 2 | VIN-номер | `string` | `Vehicle.Vin()` | +| 3 | Производитель | `string` | `Vehicle.Manufacturer()` | +| 4 | Модель | `string` | `Vehicle.Model()` | +| 5 | Год выпуска | `int` | `Random.Int(1980, текущий год)` | +| 6 | Тип корпуса | `string` | `Vehicle.Type()` | +| 7 | Тип топлива | `string` | `Vehicle.Fuel()` | +| 8 | Цвет корпуса | `string` | `Commerce.Color()` | +| 9 | Пробег (км) | `double` | `Random.Double(0, 300000)` | +| 10 | Дата последнего ТО | `DateOnly` | `Date.Between(год выпуска, сегодня)` | + +## Скриншоты + +### Aspire Dashboard +![Aspire Dashboard](images/aspire.png) + +### Клиент +![Client](images/client.png) diff --git a/VehicleApp.Api/Models/Vehicle.cs b/VehicleApp.Api/Models/Vehicle.cs new file mode 100644 index 00000000..76c261c9 --- /dev/null +++ b/VehicleApp.Api/Models/Vehicle.cs @@ -0,0 +1,57 @@ +namespace VehicleApp.Api.Models; + +/// +/// Модель транспортного средства +/// +public class Vehicle +{ + /// + /// Идентификатор в системе + /// + public int Id { get; set; } + + /// + /// VIN-номер + /// + public required string Vin { get; set; } + + /// + /// Производитель + /// + public required string Manufacturer { get; set; } + + /// + /// Модель + /// + public required string Model { get; set; } + + /// + /// Год выпуска + /// + public required int Year { get; set; } + + /// + /// Тип корпуса + /// + public required string BodyType { get; set; } + + /// + /// Тип топлива + /// + public required string FuelType { get; set; } + + /// + /// Цвет корпуса + /// + public required string BodyColor { get; set; } + + /// + /// Пробег (км) + /// + public double Mileage { get; set; } + + /// + /// Дата последнего техобслуживания + /// + public DateOnly LastServiceDate { get; set; } +} diff --git a/VehicleApp.Api/Program.cs b/VehicleApp.Api/Program.cs new file mode 100644 index 00000000..d17f7ccc --- /dev/null +++ b/VehicleApp.Api/Program.cs @@ -0,0 +1,27 @@ +using Amazon.SimpleNotificationService; +using LocalStack.Client.Extensions; +using VehicleApp.Api.Services; +using VehicleApp.Api.Services.Messaging; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddScoped(); + +builder.Services.AddScoped(); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +app.MapGet("/api/vehicles", async (int id, IVehicleService vehicleService) => +{ + var vehicle = await vehicleService.GetVehicle(id); + return Results.Ok(vehicle); +}); + +app.Run(); diff --git a/VehicleApp.Api/Properties/launchSettings.json b/VehicleApp.Api/Properties/launchSettings.json new file mode 100644 index 00000000..398f7058 --- /dev/null +++ b/VehicleApp.Api/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:38320", + "sslPort": 44373 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5204", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7069;http://localhost:5204", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/VehicleApp.Api/Services/IVehicleService.cs b/VehicleApp.Api/Services/IVehicleService.cs new file mode 100644 index 00000000..f1702ea6 --- /dev/null +++ b/VehicleApp.Api/Services/IVehicleService.cs @@ -0,0 +1,16 @@ +using VehicleApp.Api.Models; + +namespace VehicleApp.Api.Services; + +/// +/// Интерфейс сервиса для получения информации о транспортном средстве +/// +public interface IVehicleService +{ + /// + /// Получает транспортное средство по идентификатору из кэша или с помощью генератора + /// + /// Идентификатор ТС + /// Транспортное средство + public Task GetVehicle(int id); +} diff --git a/VehicleApp.Api/Services/Messaging/IVehiclePublisher.cs b/VehicleApp.Api/Services/Messaging/IVehiclePublisher.cs new file mode 100644 index 00000000..bfd1f59b --- /dev/null +++ b/VehicleApp.Api/Services/Messaging/IVehiclePublisher.cs @@ -0,0 +1,15 @@ +using VehicleApp.Api.Models; + +namespace VehicleApp.Api.Services.Messaging; + +/// +/// Отправляет ТС во внешний брокер сообщений +/// +public interface IVehiclePublisher +{ + /// + /// Публикует ТС. Вызывается только при промахе кэша, чтобы не создавать дубли + /// + /// ТС для отправки подписчикам + public Task Publish(Vehicle vehicle); +} diff --git a/VehicleApp.Api/Services/Messaging/SnsVehiclePublisher.cs b/VehicleApp.Api/Services/Messaging/SnsVehiclePublisher.cs new file mode 100644 index 00000000..90d7e375 --- /dev/null +++ b/VehicleApp.Api/Services/Messaging/SnsVehiclePublisher.cs @@ -0,0 +1,42 @@ +using System.Net; +using System.Text.Json; +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; +using VehicleApp.Api.Models; + +namespace VehicleApp.Api.Services.Messaging; + +/// +/// Реализация через Amazon SNS. +/// ТС сериализуется в JSON и отправляется в топик, ARN которого берётся из конфигурации +/// +/// SNS-клиент AWS SDK (под LocalStack указывает на контейнер) +/// Конфигурация с ключом AWS:Resources:SNSTopicArn +/// Логгер для результата публикации +public class SnsVehiclePublisher( + IAmazonSimpleNotificationService client, + IConfiguration configuration, + ILogger logger) : IVehiclePublisher +{ + private readonly string _topicArn = configuration["AWS:Resources:SNSTopicArn"] + ?? throw new KeyNotFoundException("SNS topic ARN was not found in configuration"); + + /// + public async Task Publish(Vehicle vehicle) + { + try + { + var payload = JsonSerializer.Serialize(vehicle); + var request = new PublishRequest { TopicArn = _topicArn, Message = payload }; + var response = await client.PublishAsync(request); + if (response.HttpStatusCode == HttpStatusCode.OK) + logger.LogInformation("Vehicle {id} published to SNS topic", vehicle.Id); + else + logger.LogError("Failed to publish vehicle {id}: {code}", vehicle.Id, response.HttpStatusCode); + } + catch (Exception ex) + { + logger.LogError(ex, "Exception while publishing vehicle {id} to SNS", vehicle.Id); + } + } +} diff --git a/VehicleApp.Api/Services/VehicleGenerator.cs b/VehicleApp.Api/Services/VehicleGenerator.cs new file mode 100644 index 00000000..3365dbd4 --- /dev/null +++ b/VehicleApp.Api/Services/VehicleGenerator.cs @@ -0,0 +1,32 @@ +using Bogus; +using VehicleApp.Api.Models; + +namespace VehicleApp.Api.Services; +/// +/// Генератор транспортных средств со случайными свойствами +/// +public static class VehicleGenerator +{ + private static readonly Faker _faker = new Faker() + .RuleFor(v => v.Vin, f => f.Vehicle.Vin()) + .RuleFor(v => v.Manufacturer, f => f.Vehicle.Manufacturer()) + .RuleFor(v => v.Model, f => f.Vehicle.Model()) + .RuleFor(v => v.Year, f => f.Random.Int(1980, DateTime.Now.Year)) + .RuleFor(v => v.BodyType, f => f.Vehicle.Type()) + .RuleFor(v => v.FuelType, f => f.Vehicle.Fuel()) + .RuleFor(v => v.BodyColor, f => f.Commerce.Color()) + .RuleFor(v => v.Mileage, f => Math.Round(f.Random.Double(0, 300000), 2)) + .RuleFor(v => v.LastServiceDate, (f, v) => DateOnly.FromDateTime(f.Date.Between(new DateTime(v.Year, 1, 1), DateTime.Now))); + + /// + /// Метод генерации ТС + /// + /// Идентификатор ТС + /// Транспортное средство + public static Vehicle GenerateVehicle(int id) + { + var vehicle = _faker.Generate(); + vehicle.Id = id; + return vehicle; + } +} diff --git a/VehicleApp.Api/Services/VehicleService.cs b/VehicleApp.Api/Services/VehicleService.cs new file mode 100644 index 00000000..acdbed4c --- /dev/null +++ b/VehicleApp.Api/Services/VehicleService.cs @@ -0,0 +1,69 @@ +using System.Text.Json; +using Microsoft.Extensions.Caching.Distributed; +using VehicleApp.Api.Models; +using VehicleApp.Api.Services.Messaging; + +namespace VehicleApp.Api.Services; + +/// +/// Сервис для получения информации о транспортном средстве +/// +/// Распределённый кэш +/// Публикатор ТС в брокер сообщений +/// Конфигурация приложения +/// Логгер +public class VehicleService( + IDistributedCache cache, + IVehiclePublisher publisher, + IConfiguration configuration, + ILogger logger) : IVehicleService +{ + private readonly int _expirationMinutes = configuration.GetValue("CacheSettings:ExpirationMinutes", 15); + + /// + public async Task GetVehicle(int id) + { + var cacheKey = $"vehicle-{id}"; + logger.LogInformation("Requesting vehicle {VehicleId} from cache", id); + var cachedData = await cache.GetStringAsync(cacheKey); + + if (!string.IsNullOrEmpty(cachedData)) + { + try + { + var cachedVehicle = JsonSerializer.Deserialize(cachedData); + if (cachedVehicle != null) + { + logger.LogInformation("Vehicle {VehicleId} retrieved from cache", id); + return cachedVehicle; + } + logger.LogWarning("Vehicle {VehicleId} found in cache but deserialization returned null", id); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to deserialize vehicle {VehicleId} from cache", id); + } + } + + logger.LogInformation("Vehicle {VehicleId} not found in cache. Generating", id); + + var vehicle = VehicleGenerator.GenerateVehicle(id); + + await publisher.Publish(vehicle); + + try + { + var cacheOptions = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_expirationMinutes) + }; + await cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(vehicle), cacheOptions); + logger.LogInformation("Vehicle {VehicleId} generated and cached", id); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to cache vehicle {VehicleId}. Continuing without cache.", id); + } + return vehicle; + } +} diff --git a/VehicleApp.Api/VehicleApp.Api.csproj b/VehicleApp.Api/VehicleApp.Api.csproj new file mode 100644 index 00000000..4e1a8be2 --- /dev/null +++ b/VehicleApp.Api/VehicleApp.Api.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + true + $(NoWarn);1591 + + + + + + + + + + + + + + + diff --git a/VehicleApp.Api/appsettings.Development.json b/VehicleApp.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/VehicleApp.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/VehicleApp.Api/appsettings.json b/VehicleApp.Api/appsettings.json new file mode 100644 index 00000000..3a756006 --- /dev/null +++ b/VehicleApp.Api/appsettings.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "CacheSettings": { + "ExpirationMinutes": 15 + }, + "LocalStack": { + "UseLocalStack": true + } +} diff --git a/VehicleApp.AppHost.Tests/IntegrationTest.cs b/VehicleApp.AppHost.Tests/IntegrationTest.cs new file mode 100644 index 00000000..35819fd6 --- /dev/null +++ b/VehicleApp.AppHost.Tests/IntegrationTest.cs @@ -0,0 +1,172 @@ +using System.Text.Json; +using Aspire.Hosting; +using Microsoft.Extensions.Logging; +using VehicleApp.Api.Models; +using Xunit.Abstractions; + +namespace VehicleApp.AppHost.Tests; + +/// +/// Интеграционные тесты пайплайна Gateway → Api → SNS → File.Service → Minio +/// +/// Логгер xUnit для вывода в консоль теста +public class IntegrationTest(ITestOutputHelper output) : IAsyncLifetime +{ + private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web); + + private IDistributedApplicationTestingBuilder? _builder; + private DistributedApplication? _app; + + /// + public async Task InitializeAsync() + { + var cancellationToken = CancellationToken.None; + _builder = await DistributedApplicationTestingBuilder.CreateAsync(cancellationToken); + _builder.Configuration["DcpPublisher:RandomizePorts"] = "false"; + _builder.Services.AddLogging(logging => + { + logging.AddXUnit(output); + logging.SetMinimumLevel(LogLevel.Debug); + logging.AddFilter("Aspire.Hosting.Dcp", LogLevel.Debug); + logging.AddFilter("Aspire.Hosting", LogLevel.Debug); + }); + + _app = await _builder.BuildAsync(cancellationToken); + await _app.StartAsync(cancellationToken); + } + + /// + /// Основной сценарий: запрос по id через гейтвей, затем проверка, что в Minio + /// лежит файл vehicle_{id}.json с теми же данными, что вернул API + /// + [Fact] + public async Task TestPipeline() + { + var random = new Random(); + var id = random.Next(1, 10_000); + + Assert.NotNull(_app); + using var gatewayClient = _app.CreateHttpClient("vehicleapp-gateway", "http"); + using var gatewayResponse = await gatewayClient.GetAsync($"/vehicles?id={id}"); + var apiVehicle = JsonSerializer.Deserialize(await gatewayResponse.Content.ReadAsStringAsync(), _json); + + await Task.Delay(5000); + using var fileClient = _app.CreateHttpClient("file-service", "http"); + using var listResponse = await fileClient.GetAsync("/api/s3"); + var vehicleList = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync(), _json); + using var s3Response = await fileClient.GetAsync($"/api/s3/vehicle_{id}.json"); + var s3Vehicle = JsonSerializer.Deserialize(await s3Response.Content.ReadAsStringAsync(), _json); + + Assert.NotNull(vehicleList); + Assert.Single(vehicleList); + Assert.NotNull(apiVehicle); + Assert.NotNull(s3Vehicle); + Assert.Equal(id, s3Vehicle.Id); + Assert.Equivalent(apiVehicle, s3Vehicle); + } + + /// + /// Проверяет, что файл в Minio сохраняется под ключом vehicle_{id}.json + /// + [Fact] + public async Task StoredKey_MatchesRequestedId() + { + var id = new Random().Next(1, 10_000); + + Assert.NotNull(_app); + using var gatewayClient = _app.CreateHttpClient("vehicleapp-gateway", "http"); + using var _ = await gatewayClient.GetAsync($"/vehicles?id={id}"); + + await Task.Delay(5000); + using var fileClient = _app.CreateHttpClient("file-service", "http"); + using var listResponse = await fileClient.GetAsync("/api/s3"); + var list = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync(), _json); + + Assert.NotNull(list); + Assert.Contains($"vehicle_{id}.json", list); + } + + /// + /// Запрос несуществующего ключа должен возвращать 404 + /// + [Fact] + public async Task GetFile_ReturnsNotFound_WhenKeyDoesNotExist() + { + Assert.NotNull(_app); + using var fileClient = _app.CreateHttpClient("file-service", "http"); + using var response = await fileClient.GetAsync("/api/s3/vehicle_999999.json"); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + /// + /// Повторный запрос с тем же id отдаётся из кэша и не приводит к появлению + /// второго файла в Minio + /// + [Fact] + public async Task RepeatedRequest_DoesNotDuplicateFileInMinio() + { + var id = new Random().Next(1, 10_000); + + Assert.NotNull(_app); + using var gatewayClient = _app.CreateHttpClient("vehicleapp-gateway", "http"); + using var first = await gatewayClient.GetAsync($"/vehicles?id={id}"); + var firstVehicle = JsonSerializer.Deserialize(await first.Content.ReadAsStringAsync(), _json); + + await Task.Delay(5000); + + using var second = await gatewayClient.GetAsync($"/vehicles?id={id}"); + var secondVehicle = JsonSerializer.Deserialize(await second.Content.ReadAsStringAsync(), _json); + + await Task.Delay(3000); + + using var fileClient = _app.CreateHttpClient("file-service", "http"); + using var listResponse = await fileClient.GetAsync("/api/s3"); + var list = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync(), _json); + + Assert.NotNull(firstVehicle); + Assert.NotNull(secondVehicle); + Assert.Equivalent(firstVehicle, secondVehicle); + Assert.NotNull(list); + Assert.Single(list); + Assert.Equal($"vehicle_{id}.json", list[0]); + } + + /// + /// Содержимое файла в Minio совпадает с ответом API по всем полям ТС + /// + [Fact] + public async Task StoredVehicle_HasSameFieldsAsApiResponse() + { + var id = new Random().Next(1, 10_000); + + Assert.NotNull(_app); + using var gatewayClient = _app.CreateHttpClient("vehicleapp-gateway", "http"); + using var gatewayResponse = await gatewayClient.GetAsync($"/vehicles?id={id}"); + var apiVehicle = JsonSerializer.Deserialize(await gatewayResponse.Content.ReadAsStringAsync(), _json); + + await Task.Delay(5000); + using var fileClient = _app.CreateHttpClient("file-service", "http"); + using var s3Response = await fileClient.GetAsync($"/api/s3/vehicle_{id}.json"); + var s3Vehicle = JsonSerializer.Deserialize(await s3Response.Content.ReadAsStringAsync(), _json); + + Assert.NotNull(apiVehicle); + Assert.NotNull(s3Vehicle); + Assert.Equal(apiVehicle.Id, s3Vehicle.Id); + Assert.Equal(apiVehicle.Vin, s3Vehicle.Vin); + Assert.Equal(apiVehicle.Manufacturer, s3Vehicle.Manufacturer); + Assert.Equal(apiVehicle.Model, s3Vehicle.Model); + Assert.Equal(apiVehicle.Year, s3Vehicle.Year); + Assert.Equal(apiVehicle.BodyType, s3Vehicle.BodyType); + Assert.Equal(apiVehicle.FuelType, s3Vehicle.FuelType); + Assert.Equal(apiVehicle.BodyColor, s3Vehicle.BodyColor); + } + + /// + public async Task DisposeAsync() + { + await _app!.StopAsync(); + await _app.DisposeAsync(); + await _builder!.DisposeAsync(); + } +} diff --git a/VehicleApp.AppHost.Tests/VehicleApp.AppHost.Tests.csproj b/VehicleApp.AppHost.Tests/VehicleApp.AppHost.Tests.csproj new file mode 100644 index 00000000..b89d1ac5 --- /dev/null +++ b/VehicleApp.AppHost.Tests/VehicleApp.AppHost.Tests.csproj @@ -0,0 +1,33 @@ + + + + net8.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/VehicleApp.Gateway/Program.cs b/VehicleApp.Gateway/Program.cs new file mode 100644 index 00000000..06df0922 --- /dev/null +++ b/VehicleApp.Gateway/Program.cs @@ -0,0 +1,27 @@ +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using VehicleApp.Gateway; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.Services.AddServiceDiscovery(); +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); +builder.Services.AddOcelot() + .AddCustomLoadBalancer((_, _, provider) => new(provider.GetAsync)); + +builder.Services.AddCors(options => + options.AddPolicy("AllowClient", policy => + policy.WithOrigins(builder.Configuration.GetSection("CorsSettings:AllowedOrigins").Get() ?? []) + .WithMethods("GET") + .AllowAnyHeader())); + +var app = builder.Build(); + +app.UseCors("AllowClient"); + +app.MapDefaultEndpoints(); + +await app.UseOcelot(); + +app.Run(); diff --git a/VehicleApp.Gateway/Properties/launchSettings.json b/VehicleApp.Gateway/Properties/launchSettings.json new file mode 100644 index 00000000..bb603fb5 --- /dev/null +++ b/VehicleApp.Gateway/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:38233", + "sslPort": 44380 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5262", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7163;http://localhost:5262", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/VehicleApp.Gateway/QueryBased.cs b/VehicleApp.Gateway/QueryBased.cs new file mode 100644 index 00000000..f950af7b --- /dev/null +++ b/VehicleApp.Gateway/QueryBased.cs @@ -0,0 +1,29 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace VehicleApp.Gateway; + + +/// +/// Балансировщик нагрузки на основе параметра запроса. +/// Реплика выбирается по формуле: id % N, где N — количество реплик. +/// +/// Делегат для получения списка доступных реплик сервиса. +public class QueryBased(Func>> services) : ILoadBalancer +{ + public string Type => nameof(QueryBased); + + /// Выбирает реплику на основе query-параметра id. + /// HTTP-контекст входящего запроса. + /// Хост и порт выбранной реплики. + public async Task> LeaseAsync(HttpContext context) + { + var pool = await services(); + var id = int.TryParse(context.Request.Query["id"], out var v) ? v : 0; + var target = pool[Math.Abs(id) % pool.Count]; + return new OkResponse(target.HostAndPort); + } + + public void Release(ServiceHostAndPort hostAndPort) { } +} \ No newline at end of file diff --git a/VehicleApp.Gateway/VehicleApp.Gateway.csproj b/VehicleApp.Gateway/VehicleApp.Gateway.csproj new file mode 100644 index 00000000..d0340915 --- /dev/null +++ b/VehicleApp.Gateway/VehicleApp.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/VehicleApp.Gateway/appsettings.Development.json b/VehicleApp.Gateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/VehicleApp.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/VehicleApp.Gateway/appsettings.json b/VehicleApp.Gateway/appsettings.json new file mode 100644 index 00000000..6053d188 --- /dev/null +++ b/VehicleApp.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/VehicleApp.Gateway/ocelot.json b/VehicleApp.Gateway/ocelot.json new file mode 100644 index 00000000..c39ac284 --- /dev/null +++ b/VehicleApp.Gateway/ocelot.json @@ -0,0 +1,25 @@ +{ + "Routes": [ + { + "DownstreamPathTemplate": "/api/vehicles", + "DownstreamScheme": "https", + "UpstreamPathTemplate": "/vehicles", + "UpstreamHttpMethod": [ "GET" ], + "LoadBalancerOptions": { + "Type": "QueryBased" + }, + "DownstreamHostAndPorts": [ + { "Host": "localhost", "Port": 5000 }, + { "Host": "localhost", "Port": 5001 }, + { "Host": "localhost", "Port": 5002 }, + { "Host": "localhost", "Port": 5003 }, + { "Host": "localhost", "Port": 5004 }, + { "Host": "localhost", "Port": 5005 }, + { "Host": "localhost", "Port": 5006 } + ] + } + ], + "GlobalConfiguration": { + "BaseUrl": "https://localhost:7163" + } +} diff --git a/VehicleApp/VehicleApp.AppHost/AppHost.cs b/VehicleApp/VehicleApp.AppHost/AppHost.cs new file mode 100644 index 00000000..e3418c79 --- /dev/null +++ b/VehicleApp/VehicleApp.AppHost/AppHost.cs @@ -0,0 +1,55 @@ +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("vehicle-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("vehicle-resources", "CloudFormation/vehicle-sns.yaml", "vehicle") + .WithReference(awsConfig); + +var minio = builder.AddMinioContainer("vehicle-minio"); + +var gateway = builder.AddProject("vehicleapp-gateway"); + +for (var i = 0; i < 7; i++) +{ + var service = builder.AddProject($"vehicleapp-api-{i}", launchProfileName: null) + .WithHttpsEndpoint(5000 + i) + .WithReference(redis) + .WithReference(awsResources) + .WaitFor(redis) + .WaitFor(awsResources); + gateway.WaitFor(service); +} + +builder.AddProject("client-wasm") + .WaitFor(gateway); + +builder.AddProject("file-service") + .WithReference(awsResources) + .WithReference(minio) + .WithEnvironment("AWS__Resources__MinioBucketName", "vehicle-bucket") + .WithEnvironment("AWS__Resources__SNSUrl", "http://host.docker.internal:5280/api/sns") + .WaitFor(awsResources) + .WaitFor(minio); + +builder.UseLocalStack(localstack); + +builder.Build().Run(); diff --git a/VehicleApp/VehicleApp.AppHost/CloudFormation/vehicle-sns.yaml b/VehicleApp/VehicleApp.AppHost/CloudFormation/vehicle-sns.yaml new file mode 100644 index 00000000..004887f9 --- /dev/null +++ b/VehicleApp/VehicleApp.AppHost/CloudFormation/vehicle-sns.yaml @@ -0,0 +1,29 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: 'Cloud formation template for vehicle project (SNS topic)' + +Parameters: + TopicName: + Type: String + Description: Name for the SNS topic + Default: 'vehicle-topic' + +Resources: + VehicleTopic: + 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 VehicleTopic.TopicName + + SNSTopicArn: + Description: ARN of the SNS topic + Value: !Ref VehicleTopic diff --git a/VehicleApp/VehicleApp.AppHost/Properties/launchSettings.json b/VehicleApp/VehicleApp.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..5d622e6b --- /dev/null +++ b/VehicleApp/VehicleApp.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" + } + } + } +} diff --git a/VehicleApp/VehicleApp.AppHost/VehicleApp.AppHost.csproj b/VehicleApp/VehicleApp.AppHost/VehicleApp.AppHost.csproj new file mode 100644 index 00000000..62c0e349 --- /dev/null +++ b/VehicleApp/VehicleApp.AppHost/VehicleApp.AppHost.csproj @@ -0,0 +1,33 @@ + + + + + + Exe + net8.0 + enable + enable + 2a828687-7a1a-4343-ae7d-1d2e46d714a8 + + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/VehicleApp/VehicleApp.AppHost/appsettings.Development.json b/VehicleApp/VehicleApp.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/VehicleApp/VehicleApp.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/VehicleApp/VehicleApp.AppHost/appsettings.json b/VehicleApp/VehicleApp.AppHost/appsettings.json new file mode 100644 index 00000000..a6b256bb --- /dev/null +++ b/VehicleApp/VehicleApp.AppHost/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "LocalStack": { + "UseLocalStack": true + } +} diff --git a/VehicleApp/VehicleApp.ServiceDefaults/Extensions.cs b/VehicleApp/VehicleApp.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..b72c8753 --- /dev/null +++ b/VehicleApp/VehicleApp.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/VehicleApp/VehicleApp.ServiceDefaults/VehicleApp.ServiceDefaults.csproj b/VehicleApp/VehicleApp.ServiceDefaults/VehicleApp.ServiceDefaults.csproj new file mode 100644 index 00000000..1b6e209a --- /dev/null +++ b/VehicleApp/VehicleApp.ServiceDefaults/VehicleApp.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/images/aspire.png b/images/aspire.png new file mode 100644 index 00000000..bb94f5dd Binary files /dev/null and b/images/aspire.png differ diff --git a/images/client.png b/images/client.png new file mode 100644 index 00000000..7bdb1f31 Binary files /dev/null and b/images/client.png differ