diff --git a/Api.Gateway/Api.Gateway.csproj b/Api.Gateway/Api.Gateway.csproj new file mode 100644 index 00000000..1bf624ba --- /dev/null +++ b/Api.Gateway/Api.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/Api.Gateway/Program.cs b/Api.Gateway/Program.cs new file mode 100644 index 00000000..e45ec601 --- /dev/null +++ b/Api.Gateway/Program.cs @@ -0,0 +1,34 @@ +using Api.Gateway; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.Services.AddServiceDiscovery(); +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); +builder.Services.AddOcelot() + .AddCustomLoadBalancer((sp, _, provider) => + new WeightedRoundRobin(provider.GetAsync, sp.GetRequiredService())); + +var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get() ?? []; + +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + { + policy.WithOrigins(allowedOrigins) + .AllowAnyHeader() + .WithMethods("GET"); + }); +}); + +var app = builder.Build(); + +app.UseCors(); + +app.MapDefaultEndpoints(); + +await app.UseOcelot(); + +app.Run(); diff --git a/Api.Gateway/Properties/launchSettings.json b/Api.Gateway/Properties/launchSettings.json new file mode 100644 index 00000000..7ad1b007 --- /dev/null +++ b/Api.Gateway/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:6371", + "sslPort": 44374 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5116", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7145;http://localhost:5116", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Api.Gateway/WeightedRoundRobin.cs b/Api.Gateway/WeightedRoundRobin.cs new file mode 100644 index 00000000..79b301ec --- /dev/null +++ b/Api.Gateway/WeightedRoundRobin.cs @@ -0,0 +1,56 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace Api.Gateway; + +/// +/// Балансировщик нагрузки «Взвешенная карусель» (Weighted Round Robin). +/// Реплики перебираются циклически; каждая обрабатывает ровно W запросов подряд, +/// где W — её вес из секции LoadBalancer:Weights в конфигурации (0-based). +/// +/// Делегат для получения списка доступных реплик сервиса. +/// Конфигурация приложения с секцией LoadBalancer:Weights. +public class WeightedRoundRobin( + Func>> services, + IConfiguration configuration) : ILoadBalancer +{ + public string Type => nameof(WeightedRoundRobin); + + private readonly int[] _weights = configuration.GetSection("LoadBalancer:Weights").Get() ?? []; + private readonly object _lock = new(); + private int _index; + private int _used; + + public async Task> LeaseAsync(HttpContext context) + { + var pool = await services(); + + if (pool.Count == 0) + throw new InvalidOperationException("No available downstream services"); + + lock (_lock) + { + if (_index >= pool.Count) + { + _index = 0; + _used = 0; + } + + if (_used >= Weight(_index)) + { + _index = (_index + 1) % pool.Count; + _used = 0; + } + + _used++; + return new OkResponse(pool[_index].HostAndPort); + } + } + + public void Release(ServiceHostAndPort hostAndPort) { } + + /// Возвращает вес реплики по индексу. Если не задан или не положителен — возвращает 1. + /// Индекс реплики. + private int Weight(int i) => i < _weights.Length && _weights[i] > 0 ? _weights[i] : 1; +} diff --git a/Api.Gateway/appsettings.Development.json b/Api.Gateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Api.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Api.Gateway/appsettings.json b/Api.Gateway/appsettings.json new file mode 100644 index 00000000..ba471f37 --- /dev/null +++ b/Api.Gateway/appsettings.json @@ -0,0 +1,18 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Cors": { + "AllowedOrigins": [ + "http://localhost:5127", + "https://localhost:7282" + ] + }, + "LoadBalancer": { + "Weights": [ 3, 2, 1, 1, 1 ] + } +} diff --git a/Api.Gateway/ocelot.json b/Api.Gateway/ocelot.json new file mode 100644 index 00000000..09386663 --- /dev/null +++ b/Api.Gateway/ocelot.json @@ -0,0 +1,20 @@ +{ + "Routes": [ + { + "UpstreamPathTemplate": "/vehicle", + "UpstreamHttpMethod": [ "GET" ], + "DownstreamPathTemplate": "/api/vehicle", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { "Host": "localhost", "Port": 8000 }, + { "Host": "localhost", "Port": 8001 }, + { "Host": "localhost", "Port": 8002 }, + { "Host": "localhost", "Port": 8003 }, + { "Host": "localhost", "Port": 8004 } + ], + "LoadBalancerOptions": { + "Type": "WeightedRoundRobin" + } + } + ] +} diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..8db703d5 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №3 "Интеграционное тестирование" + Вариант №27 "Транспортное средство" + Выполнила Лаврук Маргарита 6512 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea7..60120ec3 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -12,7 +12,7 @@ "http": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "http://localhost:5127", "environmentVariables": { @@ -22,7 +22,7 @@ "https": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "https://localhost:7282;http://localhost:5127", "environmentVariables": { @@ -31,7 +31,7 @@ }, "IIS Express": { "commandName": "IISExpress", - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..b6183a9a 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7145/vehicle" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..19dcbe48 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}") = "VehicleVault.AppHost", "VehicleVault\VehicleVault.AppHost\VehicleVault.AppHost.csproj", "{675E2979-6231-45C9-A79D-E8D1BE095D7E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleVault.ServiceDefaults", "VehicleVault\VehicleVault.ServiceDefaults\VehicleVault.ServiceDefaults.csproj", "{2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleVault.Api", "VehicleVault.Api\VehicleVault.Api.csproj", "{EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleVault.AppHost.Tests", "VehicleVault\VehicleVault.AppHost.Tests\VehicleVault.AppHost.Tests.csproj", "{F1B6E908-BF85-4F6D-87B9-67F2D3345D57}" +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 + {675E2979-6231-45C9-A79D-E8D1BE095D7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {675E2979-6231-45C9-A79D-E8D1BE095D7E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {675E2979-6231-45C9-A79D-E8D1BE095D7E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {675E2979-6231-45C9-A79D-E8D1BE095D7E}.Release|Any CPU.Build.0 = Release|Any CPU + {2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Release|Any CPU.Build.0 = Release|Any CPU + {EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.Release|Any CPU.Build.0 = Release|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.Build.0 = Release|Any CPU + {F1B6E908-BF85-4F6D-87B9-67F2D3345D57}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F1B6E908-BF85-4F6D-87B9-67F2D3345D57}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F1B6E908-BF85-4F6D-87B9-67F2D3345D57}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F1B6E908-BF85-4F6D-87B9-67F2D3345D57}.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/VehicleFilesController.cs b/File.Service/Controllers/VehicleFilesController.cs new file mode 100644 index 00000000..7d874925 --- /dev/null +++ b/File.Service/Controllers/VehicleFilesController.cs @@ -0,0 +1,44 @@ +using File.Service.Storage; +using Microsoft.AspNetCore.Mvc; +using System.Text.Json.Nodes; + +namespace File.Service.Controllers; + +/// +/// Контроллер для получения сохранённых в S3 файлов транспортных средств +/// +/// Сервис S3-хранилища +/// Логгер +[ApiController] +[Route("api/files")] +public class VehicleFilesController( + IVehicleStorageService storage, + ILogger logger) : ControllerBase +{ + /// + /// Возвращает список ключей файлов в бакете + /// + [HttpGet] + public async Task>> List() + { + var keys = await storage.ListKeys(); + return Ok(keys); + } + + /// + /// Возвращает JSON-файл транспортного средства по идентификатору + /// + /// Идентификатор транспортного средства + /// JSON транспортного средства; 404, если файл отсутствует + [HttpGet("{id:int}")] + public async Task> Get(int id) + { + var node = await storage.Download(IVehicleStorageService.KeyFor(id)); + if (node is null) + { + logger.LogInformation("Vehicle {Id} not found in storage", id); + return NotFound(); + } + return Ok(node); + } +} diff --git a/File.Service/File.Service.csproj b/File.Service/File.Service.csproj new file mode 100644 index 00000000..84054450 --- /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/SqsVehicleConsumerService.cs b/File.Service/Messaging/SqsVehicleConsumerService.cs new file mode 100644 index 00000000..78624ae5 --- /dev/null +++ b/File.Service/Messaging/SqsVehicleConsumerService.cs @@ -0,0 +1,68 @@ +using Amazon.SQS; +using Amazon.SQS.Model; +using File.Service.Storage; + +namespace File.Service.Messaging; + +/// +/// Фоновая служба, читающая сообщения о транспортных средствах из SQS +/// и сохраняющая их в S3-хранилище +/// +/// Клиент Amazon SQS +/// Фабрика DI-скоупа (для получения ) +/// Конфигурация (ключ AWS:Resources:SQSQueueName) +/// Логгер +public class SqsVehicleConsumerService( + 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 vehicle consumer started for queue {Queue}", _queueName); + + while (!stoppingToken.IsCancellationRequested) + { + try + { + var response = await sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest + { + QueueUrl = _queueName, + MaxNumberOfMessages = 10, + WaitTimeSeconds = 5 + }, stoppingToken); + + 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 storage = scope.ServiceProvider.GetRequiredService(); + await storage.Upload(message.Body); + await sqsClient.DeleteMessageAsync(_queueName, message.ReceiptHandle, stoppingToken); + } + catch (Exception ex) + { + logger.LogError(ex, "Error processing message {MessageId}", message.MessageId); + } + } + } + catch (OperationCanceledException) { break; } + catch (Exception ex) + { + logger.LogError(ex, "Error receiving messages from {Queue}", _queueName); + await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken); + } + } + } +} diff --git a/File.Service/Program.cs b/File.Service/Program.cs new file mode 100644 index 00000000..68aa12d0 --- /dev/null +++ b/File.Service/Program.cs @@ -0,0 +1,46 @@ +using Amazon.S3; +using Amazon.SQS; +using File.Service.Messaging; +using File.Service.Storage; +using LocalStack.Client.Extensions; +using System.Reflection; + +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 (System.IO.File.Exists(xmlPath)) + options.IncludeXmlComments(xmlPath); +}); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddAwsService(); + +builder.Services.AddScoped(); +builder.Services.AddHostedService(); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +using var scope = app.Services.CreateScope(); + +var storage = scope.ServiceProvider.GetRequiredService(); +await storage.EnsureBucketExists(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapControllers(); + +app.Run(); diff --git a/File.Service/Properties/launchSettings.json b/File.Service/Properties/launchSettings.json new file mode 100644 index 00000000..f5f38240 --- /dev/null +++ b/File.Service/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:2347", + "sslPort": 44345 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5249", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7031;http://localhost:5249", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/File.Service/Storage/IVehicleStorageService.cs b/File.Service/Storage/IVehicleStorageService.cs new file mode 100644 index 00000000..9a6d1e2b --- /dev/null +++ b/File.Service/Storage/IVehicleStorageService.cs @@ -0,0 +1,38 @@ +using System.Text.Json.Nodes; + +namespace File.Service.Storage; + +/// +/// Сервис для манипуляции файлами транспортных средств в S3-хранилище +/// +public interface IVehicleStorageService +{ + /// + /// Создаёт бакет, если он отсутствует + /// + public Task EnsureBucketExists(); + + /// + /// Сохраняет JSON-представление транспортного средства в S3 + /// + /// JSON-представление транспортного средства (ожидается поле systemId) + /// true, если файл успешно загружен + public Task Upload(string vehicleJson); + + /// + /// Возвращает список ключей файлов из бакета + /// + public Task> ListKeys(); + + /// + /// Скачивает файл по ключу и возвращает его JSON-узел + /// + /// Ключ файла + public Task Download(string key); + + /// + /// Возвращает ключ файла по идентификатору транспортного средства + /// + /// Идентификатор транспортного средства + public static string KeyFor(int id) => $"vehicle_{id}.json"; +} diff --git a/File.Service/Storage/S3VehicleStorageService.cs b/File.Service/Storage/S3VehicleStorageService.cs new file mode 100644 index 00000000..dae8a410 --- /dev/null +++ b/File.Service/Storage/S3VehicleStorageService.cs @@ -0,0 +1,97 @@ +using Amazon.S3; +using Amazon.S3.Model; +using System.Net; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace File.Service.Storage; + +/// +/// Реализация сервиса хранения файлов транспортных средств в S3 (LocalStack) +/// +/// Клиент Amazon S3 +/// Конфигурация приложения (ключ AWS:Resources:S3BucketName) +/// Логгер +public class S3VehicleStorageService( + IAmazonS3 client, + IConfiguration configuration, + ILogger logger) : IVehicleStorageService +{ + private readonly string _bucketName = configuration["AWS:Resources:S3BucketName"] + ?? throw new KeyNotFoundException("S3 bucket name was not found in configuration"); + + /// + public async Task EnsureBucketExists() + { + logger.LogInformation("Ensuring bucket {Bucket} exists", _bucketName); + await client.EnsureBucketExistsAsync(_bucketName); + } + + /// + public async Task Upload(string vehicleJson) + { + var rootNode = JsonNode.Parse(vehicleJson) + ?? throw new ArgumentException("Passed string is not a valid JSON"); + var id = rootNode["systemId"]?.GetValue() + ?? rootNode["SystemId"]?.GetValue() + ?? throw new ArgumentException("Passed JSON has no systemId field"); + + using var stream = new MemoryStream(); + JsonSerializer.Serialize(stream, rootNode); + stream.Seek(0, SeekOrigin.Begin); + + var request = new PutObjectRequest + { + BucketName = _bucketName, + Key = IVehicleStorageService.KeyFor(id), + InputStream = stream + }; + + logger.LogInformation("Uploading vehicle {Id} to bucket {Bucket}", id, _bucketName); + var response = await client.PutObjectAsync(request); + if (response.HttpStatusCode != HttpStatusCode.OK) + { + logger.LogError("Failed to upload vehicle {Id}: {Code}", id, response.HttpStatusCode); + return false; + } + return true; + } + + /// + public async Task> ListKeys() + { + var list = new List(); + var request = new ListObjectsV2Request { BucketName = _bucketName }; + var paginator = client.Paginators.ListObjectsV2(request); + await foreach (var response in paginator.Responses) + { + if (response?.S3Objects == null) continue; + foreach (var obj in response.S3Objects) + if (obj?.Key != null) + list.Add(obj.Key); + } + return list; + } + + /// + public async Task Download(string key) + { + try + { + var request = new GetObjectRequest { BucketName = _bucketName, Key = key }; + using var response = await client.GetObjectAsync(request); + if (response.HttpStatusCode != HttpStatusCode.OK) + { + logger.LogWarning("Failed to download {Key}: {Code}", key, response.HttpStatusCode); + return null; + } + using var reader = new StreamReader(response.ResponseStream, Encoding.UTF8); + return JsonNode.Parse(await reader.ReadToEndAsync()); + } + catch (AmazonS3Exception ex) when (ex.StatusCode == HttpStatusCode.NotFound) + { + return null; + } + } +} 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..10f68b8c --- /dev/null +++ b/File.Service/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/README.md b/README.md index dcaa5eb7..54dcd712 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,134 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing) - -## Задание -### Цель -Реализация проекта микросервисного бекенда. - -### Задачи -* Реализация межсервисной коммуникации, -* Изучение работы с брокерами сообщений, -* Изучение архитектурных паттернов, -* Изучение работы со средствами оркестрации на примере .NET Aspire, -* Повторение основ работы с системами контроля версий, -* Интеграционное тестирование. - -### Лабораторные работы -
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов -
- -В рамках первой лабораторной работы необходимо: -* Реализовать сервис генерации контрактов на основе Bogus, -* Реализовать кеширование при помощи IDistributedCache и Redis, -* Реализовать структурное логирование сервиса генерации, -* Настроить оркестрацию Aspire. - -
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы -
- -В рамках второй лабораторной работы необходимо: -* Настроить оркестрацию на запуск нескольких реплик сервиса генерации, -* Реализовать апи гейтвей на основе Ocelot, -* Имплементировать алгоритм балансировки нагрузки согласно варианту. - -
-
-
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда -
- -В рамках третьей лабораторной работы необходимо: -* Добавить в оркестрацию объектное хранилище, -* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище, -* Реализовать отправку генерируемых данных в файловый сервис посредством брокера, -* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе. - -
-
-
-4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud -
- -В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы: -* Клиент - в хостинг через отдельный бакет Object Storage, -* Сервис генерации - в Cloud Function, -* Апи гейтвей - в Serverless Integration как API Gateway, -* Брокер сообщений - в Message Queue, -* Файловый сервис - в Cloud Function, -* Объектное хранилище - в отдельный бакет Object Storage, - -
-
- -## Задание. Общая часть -**Обязательно**: -* Реализация серверной части на [.NET 8](https://learn.microsoft.com/ru-ru/dotnet/core/whats-new/dotnet-8/overview). -* Оркестрация проектов при помощи [.NET Aspire](https://learn.microsoft.com/ru-ru/dotnet/aspire/get-started/aspire-overview). -* Реализация сервиса генерации данных при помощи [Bogus](https://github.com/bchavez/Bogus). -* Реализация тестов с использованием [xUnit](https://xunit.net/?tabs=cs). -* Создание минимальной документации к проекту: страница на GitHub с информацией о задании, скриншоты приложения и прочая информация. - -**Факультативно**: -* Перенос бекенда на облачную инфраструктуру Yandex Cloud - -Внимательно прочитайте [дискуссии](https://github.com/itsecd/cloud-development/discussions/1) о том, как работает автоматическое распределение на ревью. -Сразу корректно называйте свои pr, чтобы они попали на ревью нужному преподавателю. - -По итогу работы в семестре должна получиться следующая информационная система: -
-C4 диаграмма -Современные_технологии_разработки_ПО_drawio -
- -## Варианты заданий -Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи. - -[Список вариантов](https://docs.google.com/document/d/1WGmLYwffTTaAj4TgFCk5bUyW3XKbFMiBm-DHZrfFWr4/edit?usp=sharing) -[Список предметных областей и алгоритмов балансировки](https://docs.google.com/document/d/1PLn2lKe4swIdJDZhwBYzxqFSu0AbY2MFY1SUPkIKOM4/edit?usp=sharing) - -## Схема сдачи - -На каждую из лабораторных работ необходимо сделать отдельный [Pull Request (PR)](https://docs.github.com/en/pull-requests). - -Общая схема: -1. Сделать форк данного репозитория -2. Выполнить задание -3. Сделать PR в данный репозиторий -4. Исправить замечания после code review -5. Получить approve - -## Критерии оценивания - -Конкурентный принцип. -Так как задания в первой лабораторной будут повторяться между студентами, то выделяются следующие показатели для оценки: -1. Скорость разработки -2. Качество разработки -3. Полнота выполнения задания - -Быстрее делаете PR - у вас преимущество. -Быстрее получаете Approve - у вас преимущество. -Выполните нечто немного выходящее за рамки проекта - у вас преимущество. -Не укладываетесь в дедлайн - получаете минимально возможный балл. - -### Шкала оценивания - -- **3 балла** за качество кода, из них: - - 2 балла - базовая оценка - - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов: - - Реализация факультативного функционала - - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл - -## Вопросы и обратная связь по курсу - -Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](https://github.com/itsecd/cloud-development/discussions/categories/questions) или заведите [ишью](https://github.com/itsecd/cloud-development/issues/new). -Если у вас появились идеи/пожелания/прочие полезные мысли по преподаваемой дисциплине, их можно оставить [здесь](https://github.com/itsecd/cloud-development/discussions/categories/ideas). +# Лабораторная работа №1 «Кэширование» +## Описание + +Реализация сервиса генерации данных о транспортных средствах с кэшированием ответов в Redis. +Оркестрация проектов при помощи .NET Aspire. + +## Технологии + +- .NET 8 +- .NET Aspire 9.5 +- Bogus — генерация фейковых данных +- Redis — распределённое кэширование (`IDistributedCache`) +- Blazor WebAssembly — клиентское приложение +- Blazorise — UI-компоненты +- OpenTelemetry — структурное логирование и трассировка + +## Характеристики генерируемого объекта + +| № | Характеристика | Тип данных | Источник Bogus | +|---|---|---|---| +| 1 | Идентификатор в системе | `int` | Параметр запроса | +| 2 | VIN-номер | `string` | `Vehicle.Vin()` | +| 3 | Производитель | `string` | `Vehicle.Manufacturer()` | +| 4 | Модель | `string` | `Vehicle.Model()` | +| 5 | Год выпуска | `int` | `Random.Int(1960, текущий год)` | +| 6 | Тип корпуса | `string` | `Vehicle.Type()` | +| 7 | Тип топлива | `string` | `Vehicle.Fuel()` | +| 8 | Цвет корпуса | `string` | `Commerce.Color()` | +| 9 | Пробег | `double` | `Random.Double(0, 1000000)` | +| 10 | Дата последнего техобслуживания | `DateOnly` | Между годом выпуска и текущей датой | + +### Кэширование + +- Ключ кэша: `vehicle:{id}` +- Время жизни: настраивается в `appsettings.json` (`Cache:ExpirationMinutes`, по умолчанию 5 минут) +- При ошибке чтения/записи кэша — логируется warning, запрос обрабатывается без кэша + +## API + +``` +GET /api/vehicle?id={id} +``` + +Возвращает JSON с данными транспортного средства. При повторном запросе с тем же `id` — данные берутся из кэша Redis. + +--- + +# Лабораторная работа №2 «Балансировка нагрузки» + +## Описание + +Реализация API-шлюза на основе Ocelot с алгоритмом балансировки нагрузки **Weighted Round Robin**. +Оркестрация запускает несколько реплик сервиса генерации через .NET Aspire. + +## Алгоритм: Weighted Round Robin + +Каждой реплике присваивается числовой вес из конфигурации (`LoadBalancer:Weights` в `appsettings.json` шлюза). +Реплики перебираются циклически; реплика с весом `W` обрабатывает `W` запросов подряд перед переходом к следующей. + +### Конфигурация весов (`Api.Gateway/appsettings.json`) + +```json +"LoadBalancer": { + "Weights": [ 3, 2, 1, 1, 1 ] +} +``` + +Индекс массива соответствует порядковому номеру реплики (0-based). Если вес не задан — используется значение `1`. + +## Оркестрация реплик (`VehicleVault.AppHost`) + +Aspire запускает 5 независимых экземпляров `VehicleVault.Api` на портах `8000–8004`: + +--- + +# Лабораторная работа №3 «Файловое хранилище и брокер сообщений» + +## Описание + +Расширение пайплайна асинхронной выгрузкой сгенерированных транспортных средств в объектное +хранилище. После генерации `VehicleVault.Api` отправляет JSON-представление ТС в очередь **AWS SQS**; +файловый сервис `File.Service` фоново читает очередь и складывает каждый объект в **S3-бакет** +(имя файла — `vehicle_{id}.json`). Очередь и бакет поднимаются эмулятором **LocalStack**, который +оркеструется через Aspire и инициализируется CloudFormation-шаблоном. + +> **Вариант лабораторной:** SQS + LocalStack S3 + +## Технологии + +- AWSSDK.SQS, AWSSDK.S3 — клиенты AWS +- LocalStack.Client + LocalStack.Client.Extensions — переадресация AWS SDK на LocalStack +- LocalStack.Aspire.Hosting — запуск контейнера LocalStack из Aspire +- CloudFormation — декларативное создание SQS-очереди и S3-бакета +- AWSSDK CloudFormation (через Aspire.Hosting.AWS, транзитивно) — применение шаблона + +## Имена ресурсов и параметры + +CloudFormation-шаблон [`VehicleVault.AppHost/CloudFormation/vehiclevault-template.yaml`](VehicleVault/VehicleVault.AppHost/CloudFormation/vehiclevault-template.yaml) +создаёт два ресурса: + +| Ресурс | Имя по умолчанию | Параметры | +|-------------------|-----------------------|----------------------------------------------------------| +| `AWS::SQS::Queue` | `vehiclevault-queue` | VisibilityTimeout=30s, MessageRetentionPeriod=4 дня | +| `AWS::S3::Bucket` | `vehiclevault-bucket` | Versioning=Suspended, public access заблокирован | + +Имена прокидываются в сервисы через `Outputs` шаблона (`SQSQueueName`, `S3BucketName`) +и читаются из конфигурации по ключам `AWS:Resources:SQSQueueName` и `AWS:Resources:S3BucketName`. + +## S3-сервис + +`S3VehicleStorageService` ([File.Service/Storage/S3VehicleStorageService.cs](File.Service/Storage/S3VehicleStorageService.cs)): + +- `EnsureBucketExists()` — вызывается при старте `File.Service`. +- `Upload(json)` — сохраняет ТС с ключом `vehicle_{SystemId}.json`. +- `Download(key)` / `ListKeys()` — чтение для эндпоинтов проверки. + +## API файлового сервиса + +``` +GET /api/files — список ключей файлов в бакете +GET /api/files/{id} — JSON транспортного средства; 404, если файла нет +``` + +Используется интеграционным тестом и пригоден для ручной проверки через Swagger. + +## Интеграционный тест + +[VehicleVault.AppHost.Tests/IntegrationTest.cs](VehicleVault/VehicleVault.AppHost.Tests/IntegrationTest.cs): + +1. Поднимает весь Aspire-граф через `DistributedApplicationTestingBuilder`. +2. Дёргает `GET /vehicle?id={id}` через `api-gateway`. +3. Ждёт 5 секунд (за это время SQS-консьюмер должен забрать сообщение и положить файл в S3) и читает `GET /api/files/{id}` у `file-service`. +4. Сравнивает ответ гейтвея с содержимым файла в S3 (`Assert.Equivalent`). diff --git a/VehicleVault.Api/Entities/Vehicle.cs b/VehicleVault.Api/Entities/Vehicle.cs new file mode 100644 index 00000000..f04911c8 --- /dev/null +++ b/VehicleVault.Api/Entities/Vehicle.cs @@ -0,0 +1,57 @@ +namespace VehicleVault.Api.Entities; + +/// +/// Транспортное средство +/// +public class Vehicle +{ + /// + /// Идентификатор в системе + /// + public int SystemId { get; set; } + + /// + /// VIN-номер + /// + public required string Vin { get; set; } + + /// + /// Производитель + /// + public required string Manufacturer { get; set; } + + /// + /// Модель + /// + public required string Model { get; set; } + + /// + /// Год выпуска + /// + public 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/VehicleVault.Api/Program.cs b/VehicleVault.Api/Program.cs new file mode 100644 index 00000000..9cc213bc --- /dev/null +++ b/VehicleVault.Api/Program.cs @@ -0,0 +1,24 @@ +using Amazon.SQS; +using LocalStack.Client.Extensions; +using VehicleVault.Api.Services; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("cache"); + +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddSingleton(); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +app.MapGet("api/vehicle", async (int id, IVehicleCacheService vehicleService) => + await vehicleService.GetOrGenerate(id)); + +app.Run(); diff --git a/VehicleVault.Api/Properties/launchSettings.json b/VehicleVault.Api/Properties/launchSettings.json new file mode 100644 index 00000000..304fa877 --- /dev/null +++ b/VehicleVault.Api/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:12998", + "sslPort": 44340 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5260", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7283;http://localhost:5260", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/VehicleVault.Api/Services/IVehicleCacheService.cs b/VehicleVault.Api/Services/IVehicleCacheService.cs new file mode 100644 index 00000000..2c234b63 --- /dev/null +++ b/VehicleVault.Api/Services/IVehicleCacheService.cs @@ -0,0 +1,14 @@ +using VehicleVault.Api.Entities; + +namespace VehicleVault.Api.Services; + +/// +/// Сервис транспортных средств с кэшированием +/// +public interface IVehicleCacheService +{ + /// + /// Получение или генерация транспортного средства по идентификатору + /// + public Task GetOrGenerate(int id); +} diff --git a/VehicleVault.Api/Services/IVehicleGeneratorService.cs b/VehicleVault.Api/Services/IVehicleGeneratorService.cs new file mode 100644 index 00000000..b8964bc9 --- /dev/null +++ b/VehicleVault.Api/Services/IVehicleGeneratorService.cs @@ -0,0 +1,14 @@ +using VehicleVault.Api.Entities; + +namespace VehicleVault.Api.Services; + +/// +/// Сервис генерации данных транспортного средства +/// +public interface IVehicleGeneratorService +{ + /// + /// Генерация транспортного средства по идентификатору + /// + public Vehicle Generate(int id); +} diff --git a/VehicleVault.Api/Services/IVehiclePublisherService.cs b/VehicleVault.Api/Services/IVehiclePublisherService.cs new file mode 100644 index 00000000..420b451a --- /dev/null +++ b/VehicleVault.Api/Services/IVehiclePublisherService.cs @@ -0,0 +1,15 @@ +using VehicleVault.Api.Entities; + +namespace VehicleVault.Api.Services; + +/// +/// Сервис отправки сгенерированного транспортного средства в брокер сообщений +/// +public interface IVehiclePublisherService +{ + /// + /// Отправляет транспортное средство в очередь + /// + /// Транспортное средство + public Task Publish(Vehicle vehicle); +} diff --git a/VehicleVault.Api/Services/SqsVehiclePublisherService.cs b/VehicleVault.Api/Services/SqsVehiclePublisherService.cs new file mode 100644 index 00000000..25f72e7f --- /dev/null +++ b/VehicleVault.Api/Services/SqsVehiclePublisherService.cs @@ -0,0 +1,39 @@ +using Amazon.SQS; +using System.Net; +using System.Text.Json; +using VehicleVault.Api.Entities; + +namespace VehicleVault.Api.Services; + +/// +/// Сервис отправки транспортного средства в очередь SQS +/// +/// Клиент Amazon SQS +/// Конфигурация приложения (используется ключ AWS:Resources:SQSQueueName) +/// Логгер +public class SqsVehiclePublisherService( + IAmazonSQS client, + IConfiguration configuration, + ILogger logger) : IVehiclePublisherService +{ + private readonly string _queueName = configuration["AWS:Resources:SQSQueueName"] + ?? throw new KeyNotFoundException("SQS queue name was not found in configuration"); + + /// + public async Task Publish(Vehicle vehicle) + { + try + { + var json = JsonSerializer.Serialize(vehicle); + var response = await client.SendMessageAsync(_queueName, json); + if (response.HttpStatusCode == HttpStatusCode.OK) + logger.LogInformation("Vehicle {Id} sent to SQS queue {Queue}", vehicle.SystemId, _queueName); + else + throw new InvalidOperationException($"SQS returned {response.HttpStatusCode}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to publish vehicle {Id} to SQS", vehicle.SystemId); + } + } +} diff --git a/VehicleVault.Api/Services/VehicleCacheService.cs b/VehicleVault.Api/Services/VehicleCacheService.cs new file mode 100644 index 00000000..2c7926d5 --- /dev/null +++ b/VehicleVault.Api/Services/VehicleCacheService.cs @@ -0,0 +1,85 @@ +using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; +using VehicleVault.Api.Entities; + +namespace VehicleVault.Api.Services; + +/// +/// Сервис транспортных средств с кэшированием +/// +/// Генератор транспортных средств +/// Сервис отправки сгенерированных ТС в брокер сообщений +/// Распределённый кэш +/// Конфигурация приложения +/// Логгер +public class VehicleCacheService( + IVehicleGeneratorService vehicleGenerator, + IVehiclePublisherService vehiclePublisher, + IDistributedCache distributedCache, + IConfiguration appConfiguration, + ILogger logger) : IVehicleCacheService +{ + private readonly TimeSpan _entryLifetime = TimeSpan.FromMinutes(appConfiguration.GetValue("Cache:ExpirationMinutes", 5)); + + /// + public async Task GetOrGenerate(int id) + { + var key = $"vehicle:{id}"; + + var existing = await TryGetFromCache(key); + if (existing is not null) + return existing; + + logger.LogInformation("Cache miss for id {Id}, generating new vehicle", id); + var result = vehicleGenerator.Generate(id); + await TrySaveToCache(key, result); + await vehiclePublisher.Publish(result); + + return result; + } + + /// + /// Попытка получить транспортное средство из кэша + /// + /// Ключ записи + /// Транспортное средство или null + private async Task TryGetFromCache(string key) + { + try + { + var data = await distributedCache.GetStringAsync(key); + if (data is null) + return null; + + logger.LogInformation("Cache hit for key {Key}", key); + return JsonSerializer.Deserialize(data); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to retrieve from cache by key {Key}", key); + return null; + } + } + + /// + /// Попытка сохранить транспортное средство в кэш + /// + /// Ключ записи + /// Транспортное средство + private async Task TrySaveToCache(string key, Vehicle vehicle) + { + try + { + var serialized = JsonSerializer.Serialize(vehicle); + await distributedCache.SetStringAsync(key, serialized, new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _entryLifetime + }); + logger.LogInformation("Saved to cache with key {Key}", key); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to save to cache by key {Key}", key); + } + } +} diff --git a/VehicleVault.Api/Services/VehicleGeneratorService.cs b/VehicleVault.Api/Services/VehicleGeneratorService.cs new file mode 100644 index 00000000..2781c834 --- /dev/null +++ b/VehicleVault.Api/Services/VehicleGeneratorService.cs @@ -0,0 +1,30 @@ +using Bogus; +using VehicleVault.Api.Entities; + +namespace VehicleVault.Api.Services; + +/// +/// Реализация сервиса генерации данных транспортного средства +/// +public class VehicleGeneratorService : IVehicleGeneratorService +{ + private 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(1960, 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, 1000000), 3)) + .RuleFor(v => v.LastServiceDate, (f, v) => + DateOnly.FromDateTime(f.Date.Between(new DateTime(v.Year, 1, 1), DateTime.Now))); + + /// + public Vehicle Generate(int id) + { + var vehicle = _faker.Generate(); + vehicle.SystemId = id; + return vehicle; + } +} diff --git a/VehicleVault.Api/VehicleVault.Api.csproj b/VehicleVault.Api/VehicleVault.Api.csproj new file mode 100644 index 00000000..fbaa62b8 --- /dev/null +++ b/VehicleVault.Api/VehicleVault.Api.csproj @@ -0,0 +1,21 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + diff --git a/VehicleVault.Api/appsettings.Development.json b/VehicleVault.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/VehicleVault.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/VehicleVault.Api/appsettings.json b/VehicleVault.Api/appsettings.json new file mode 100644 index 00000000..4b07986a --- /dev/null +++ b/VehicleVault.Api/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Cache": { + "ExpirationMinutes": 5 + } +} diff --git a/VehicleVault/VehicleVault.AppHost.Tests/IntegrationTest.cs b/VehicleVault/VehicleVault.AppHost.Tests/IntegrationTest.cs new file mode 100644 index 00000000..80588c13 --- /dev/null +++ b/VehicleVault/VehicleVault.AppHost.Tests/IntegrationTest.cs @@ -0,0 +1,76 @@ +using Aspire.Hosting; +using Microsoft.Extensions.Logging; +using System.Text.Json; +using VehicleVault.Api.Entities; +using Xunit.Abstractions; + +namespace VehicleVault.AppHost.Tests; + +/// +/// Интеграционные тесты пайплайна +/// +/// Журнал для xUnit +public class IntegrationTest(ITestOutputHelper output) : IAsyncLifetime +{ + private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); + private DistributedApplication? _app; + + /// + public async Task InitializeAsync() + { + var ct = CancellationToken.None; + var builder = await DistributedApplicationTestingBuilder.CreateAsync(ct); + 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(ct); + await _app.StartAsync(ct); + } + + /// + /// Дёргает эндпоинт API-Gateway с заданным id, ждёт обработки сообщения SQS-консьюмером + /// и проверяет, что в S3-хранилище появился файл с этим же id + /// + [Fact] + public async Task GatewayRequest_ShouldStoreVehicleFileInS3() + { + var ct = CancellationToken.None; + var id = new Random().Next(1, 100); + + using var gatewayClient = _app!.CreateHttpClient("api-gateway", "http"); + using var gatewayResponse = await gatewayClient.GetAsync($"/vehicle?id={id}", ct); + Assert.Equal(HttpStatusCode.OK, gatewayResponse.StatusCode); + + var apiVehicle = JsonSerializer.Deserialize( + await gatewayResponse.Content.ReadAsStringAsync(ct), _jsonOptions); + Assert.NotNull(apiVehicle); + Assert.Equal(id, apiVehicle!.SystemId); + + await Task.Delay(TimeSpan.FromSeconds(5), ct); + + using var fileClient = _app!.CreateHttpClient("file-service", "http"); + using var fileResponse = await fileClient.GetAsync($"/api/files/{id}", ct); + Assert.Equal(HttpStatusCode.OK, fileResponse.StatusCode); + + var s3Vehicle = JsonSerializer.Deserialize( + await fileResponse.Content.ReadAsStringAsync(ct), _jsonOptions); + + Assert.NotNull(s3Vehicle); + Assert.Equal(id, s3Vehicle!.SystemId); + Assert.Equivalent(apiVehicle, s3Vehicle); + } + + /// + public async Task DisposeAsync() + { + if (_app is null) return; + await _app.StopAsync(); + await _app.DisposeAsync(); + } +} diff --git a/VehicleVault/VehicleVault.AppHost.Tests/VehicleVault.AppHost.Tests.csproj b/VehicleVault/VehicleVault.AppHost.Tests/VehicleVault.AppHost.Tests.csproj new file mode 100644 index 00000000..031394d1 --- /dev/null +++ b/VehicleVault/VehicleVault.AppHost.Tests/VehicleVault.AppHost.Tests.csproj @@ -0,0 +1,33 @@ + + + + net8.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/VehicleVault/VehicleVault.AppHost/AppHost.cs b/VehicleVault/VehicleVault.AppHost/AppHost.cs new file mode 100644 index 00000000..1c403a4c --- /dev/null +++ b/VehicleVault/VehicleVault.AppHost/AppHost.cs @@ -0,0 +1,48 @@ +using Amazon; +using Aspire.Hosting.LocalStack.Container; + +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("cache") + .WithRedisInsight(); + +var awsConfig = builder.AddAWSSDKConfig() + .WithProfile("default") + .WithRegion(RegionEndpoint.EUCentral1); + +var localstack = builder.AddLocalStack("vehiclevault-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("vehiclevault-resources", "CloudFormation/vehiclevault-template.yaml", "vehiclevault") + .WithReference(awsConfig); + +var apiGateway = builder.AddProject("api-gateway"); + +for (var i = 0; i < 5; i++) +{ + var api = builder.AddProject($"vehiclevault-api-{i}", launchProfileName: null) + .WithHttpsEndpoint(8000 + i) + .WithReference(cache) + .WithReference(awsResources) + .WaitFor(cache) + .WaitFor(awsResources); + apiGateway.WaitFor(api); +} + +builder.AddProject("client-wasm") + .WaitFor(apiGateway); + +builder.AddProject("file-service") + .WithReference(awsResources) + .WaitFor(awsResources); + +builder.UseLocalStack(localstack); + +builder.Build().Run(); diff --git a/VehicleVault/VehicleVault.AppHost/CloudFormation/vehiclevault-template.yaml b/VehicleVault/VehicleVault.AppHost/CloudFormation/vehiclevault-template.yaml new file mode 100644 index 00000000..cb16dd88 --- /dev/null +++ b/VehicleVault/VehicleVault.AppHost/CloudFormation/vehiclevault-template.yaml @@ -0,0 +1,62 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: 'CloudFormation template for VehicleVault project (SQS + S3)' + +Parameters: + BucketName: + Type: String + Description: Name for the S3 bucket + Default: 'vehiclevault-bucket' + + QueueName: + Type: String + Description: Name for the SQS queue + Default: 'vehiclevault-queue' + +Resources: + VehicleVaultBucket: + Type: AWS::S3::Bucket + Properties: + BucketName: !Ref BucketName + VersioningConfiguration: + Status: Suspended + Tags: + - Key: Name + Value: !Ref BucketName + - Key: Environment + Value: VehicleVault + PublicAccessBlockConfiguration: + BlockPublicAcls: true + BlockPublicPolicy: true + IgnorePublicAcls: true + RestrictPublicBuckets: true + + VehicleVaultQueue: + 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: VehicleVault + +Outputs: + S3BucketName: + Description: Name of the S3 bucket + Value: !Ref VehicleVaultBucket + + S3BucketArn: + Description: ARN of the S3 bucket + Value: !GetAtt VehicleVaultBucket.Arn + + SQSQueueName: + Description: Name of the SQS queue + Value: !GetAtt VehicleVaultQueue.QueueName + + SQSQueueArn: + Description: ARN of the SQS queue + Value: !GetAtt VehicleVaultQueue.Arn diff --git a/VehicleVault/VehicleVault.AppHost/Properties/launchSettings.json b/VehicleVault/VehicleVault.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..e61ad6be --- /dev/null +++ b/VehicleVault/VehicleVault.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:17060;http://localhost:15002", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21017", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22019" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15002", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19170", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20000" + } + } + } +} diff --git a/VehicleVault/VehicleVault.AppHost/VehicleVault.AppHost.csproj b/VehicleVault/VehicleVault.AppHost/VehicleVault.AppHost.csproj new file mode 100644 index 00000000..92596d42 --- /dev/null +++ b/VehicleVault/VehicleVault.AppHost/VehicleVault.AppHost.csproj @@ -0,0 +1,32 @@ + + + + + + Exe + net8.0 + enable + enable + e8350e86-dfa1-4c37-9efc-069d9ff7570f + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/VehicleVault/VehicleVault.AppHost/appsettings.Development.json b/VehicleVault/VehicleVault.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/VehicleVault/VehicleVault.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/VehicleVault/VehicleVault.AppHost/appsettings.json b/VehicleVault/VehicleVault.AppHost/appsettings.json new file mode 100644 index 00000000..a6b256bb --- /dev/null +++ b/VehicleVault/VehicleVault.AppHost/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "LocalStack": { + "UseLocalStack": true + } +} diff --git a/VehicleVault/VehicleVault.ServiceDefaults/Extensions.cs b/VehicleVault/VehicleVault.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..b72c8753 --- /dev/null +++ b/VehicleVault/VehicleVault.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/VehicleVault/VehicleVault.ServiceDefaults/VehicleVault.ServiceDefaults.csproj b/VehicleVault/VehicleVault.ServiceDefaults/VehicleVault.ServiceDefaults.csproj new file mode 100644 index 00000000..1b6e209a --- /dev/null +++ b/VehicleVault/VehicleVault.ServiceDefaults/VehicleVault.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + +