diff --git a/ApiGateway/ApiGateway.csproj b/ApiGateway/ApiGateway.csproj new file mode 100644 index 00000000..0ba257f0 --- /dev/null +++ b/ApiGateway/ApiGateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/ApiGateway/LoadBalancer/WeightedRandomBalancer.cs b/ApiGateway/LoadBalancer/WeightedRandomBalancer.cs new file mode 100644 index 00000000..82b40527 --- /dev/null +++ b/ApiGateway/LoadBalancer/WeightedRandomBalancer.cs @@ -0,0 +1,80 @@ +using Ocelot.LoadBalancer.Errors; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace ApiGateway.LoadBalancer; + +/// +/// Балансировщик с взвешенным случайным выбором реплики сервиса. +/// +/// Все доступные экземпляры сервиса из service discovery. +/// Набор весов для эндпоинтов в формате name:"service-name-{i}" value:"weight". +/// +public class WeightedRandomBalancer(Func>> services, Dictionary weights) : ILoadBalancer +{ + public string Type => nameof(WeightedRandomBalancer); + + /// + /// Выбирает реплику сервиса по алгоритму weighted random. + /// + /// Список доступных сервисов. + /// Словарь весов для всех сервисов. + /// Выбранная реплика сервиса. + private static Service GetServiceByWeight(List services, Dictionary weights) + { + var cumulativeWeights = new double[services.Count]; + var sum = 0.0; + for (var i = 0; i < services.Count; ++i) + { + var service = services[i]; + var key = $"{service.HostAndPort.DownstreamHost}_{service.HostAndPort.DownstreamPort}"; + var weight = weights.TryGetValue(key, out var w) ? w : 1.0; + + sum += weight; + cumulativeWeights[i] = sum; + } + + if (sum <= 0) + { + return services[Random.Shared.Next(services.Count)]; + } + + var randomValue = Random.Shared.NextDouble() * sum; + + var index = Array.BinarySearch(cumulativeWeights, randomValue); + if (index < 0) + { + index = ~index; + } + index = Math.Min(index, services.Count - 1); + + return services[index]; + } + + /// + /// Выдает эндпоинт сервиса для текущего запроса. + /// + /// Контекст входящего запроса. + /// Выбранный адрес сервиса или ошибка, если сервисы недоступны. + public async Task> LeaseAsync(HttpContext httpContext) + { + var allServices = await services.Invoke(); + if (allServices == null || allServices.Count == 0) + { + return new ErrorResponse( + new ServicesAreNullError("No services available") + ); + } + + var selectedService = GetServiceByWeight(allServices, weights); + + return new OkResponse(selectedService.HostAndPort); + } + + /// + /// Освобождает ранее выданный эндпоинт. + /// + /// Адрес освобождаемого сервиса. + public void Release(ServiceHostAndPort serviceHostAndPort) { } +} diff --git a/ApiGateway/Program.cs b/ApiGateway/Program.cs new file mode 100644 index 00000000..b0597d77 --- /dev/null +++ b/ApiGateway/Program.cs @@ -0,0 +1,94 @@ +using ApiGateway.LoadBalancer; +using AppHost.ServiceDefaults; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using System.Globalization; + +static (Dictionary RouteOverrides, Dictionary weights) + BuildEnv(IConfiguration configuration) +{ + var namedWeights = configuration + .GetSection("LoadBalancerWeights") + .Get>() ?? []; + + var routeOverrides = new Dictionary(); + var weights = new Dictionary(); + + Uri? firstEndpoint = null; + for (var i = 0; i < 5; ++i) + { + var envKey = $"services__generation-service-{i}__http__0"; + var raw = Environment.GetEnvironmentVariable(envKey); + if (string.IsNullOrWhiteSpace(raw)) + continue; + + if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri)) + throw new InvalidOperationException($"Invalid endpoint in {envKey}: {raw}"); + + firstEndpoint ??= uri; + + routeOverrides[$"Routes:0:DownstreamHostAndPorts:{i}:Host"] = uri.Host; + routeOverrides[$"Routes:0:DownstreamHostAndPorts:{i}:Port"] = + uri.Port.ToString(CultureInfo.InvariantCulture); + + var key = $"{uri.Host}_{uri.Port}"; + var serviceName = $"generation-service-{i}"; + weights[key] = namedWeights.TryGetValue(serviceName, out var w) ? w : 1.0; + } + + routeOverrides["Routes:0:DownstreamScheme"] = firstEndpoint!.Scheme; + + return (routeOverrides, weights); +} + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.Services.AddServiceDiscovery(); +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); + +var (routeOverrides, weights) = BuildEnv(builder.Configuration); +builder.Configuration.AddInMemoryCollection(routeOverrides); + +builder.Services + .AddOcelot() + .AddCustomLoadBalancer((_, _, discoveryProvider) => new(discoveryProvider.GetAsync, weights)); + +var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get(); +var allowedMethods = builder.Configuration.GetSection("Cors:AllowedMethods").Get(); +var allowedHeaders = builder.Configuration.GetSection("Cors:AllowedHeaders").Get(); +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + { + if (allowedOrigins != null) + { + _ = allowedOrigins.Contains("*") + ? policy.AllowAnyOrigin() + : policy.WithOrigins(allowedOrigins); + } + + if (allowedMethods != null) + { + _ = allowedMethods.Contains("*") + ? policy.AllowAnyMethod() + : policy.WithMethods(allowedMethods); + } + + if (allowedHeaders != null) + { + _ = allowedHeaders.Contains("*") + ? policy.AllowAnyHeader() + : policy.WithHeaders(allowedHeaders); + } + }); +}); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); +app.UseCors(); + +await app.UseOcelot(); + +app.Run(); \ No newline at end of file diff --git a/ApiGateway/Properties/launchSettings.json b/ApiGateway/Properties/launchSettings.json new file mode 100644 index 00000000..7898f46b --- /dev/null +++ b/ApiGateway/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5254", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7268;http://localhost:5254", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/ApiGateway/appsettings.Development.json b/ApiGateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/ApiGateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/ApiGateway/appsettings.json b/ApiGateway/appsettings.json new file mode 100644 index 00000000..7a0700bc --- /dev/null +++ b/ApiGateway/appsettings.json @@ -0,0 +1,17 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "ConnectionStrings": { + "RedisCache": "https://localhost:2843" + }, + "Cors": { + "AllowedOrigins": [ "https://localhost:7282" ], + "AllowedMethods": [ "GET" ], + "AllowedHeaders": [ "*" ] + } +} diff --git a/ApiGateway/ocelot.json b/ApiGateway/ocelot.json new file mode 100644 index 00000000..4c6114f0 --- /dev/null +++ b/ApiGateway/ocelot.json @@ -0,0 +1,21 @@ +{ + "Routes": [ + { + "DownstreamPathTemplate": "/patient", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [], + "UpstreamPathTemplate": "/patient", + "UpstreamHttpMethod": [ "Get" ], + "LoadBalancerOptions": { + "Type": "WeightedRandomBalancer" + } + } + ], + "LoadBalancerWeights": { + "generation-service-0": 0.4, + "generation-service-1": 0.25, + "generation-service-2": 0.15, + "generation-service-3": 0.1, + "generation-service-4": 0.1 + } +} \ No newline at end of file diff --git a/AppHost/AppHost.AppHost/AppHost.AppHost.csproj b/AppHost/AppHost.AppHost/AppHost.AppHost.csproj new file mode 100644 index 00000000..2a71824c --- /dev/null +++ b/AppHost/AppHost.AppHost/AppHost.AppHost.csproj @@ -0,0 +1,30 @@ + + + + Exe + net8.0 + enable + enable + 96fbf34e-00b4-4158-9be4-e6f641d5c362 + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/AppHost/AppHost.AppHost/AppHost.cs b/AppHost/AppHost.AppHost/AppHost.cs new file mode 100644 index 00000000..ad8189ad --- /dev/null +++ b/AppHost/AppHost.AppHost/AppHost.cs @@ -0,0 +1,58 @@ +using Amazon; +using Aspire.Hosting.LocalStack.Container; + +var builder = DistributedApplication.CreateBuilder(args); + +var awsConfig = builder.AddAWSSDKConfig() + .WithProfile("default") + .WithRegion(RegionEndpoint.EUCentral1); + +var localstack = builder + .AddLocalStack("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 cloudFormationTemplate = "CloudFormation/event-sink-sns-localstack.yaml"; +var awsResources = builder.AddAWSCloudFormationTemplate("resources", cloudFormationTemplate, "event-sink") + .WithReference(awsConfig) + .WaitFor(localstack!); + +var cache = builder.AddRedis("cache") + .WithRedisInsight(containerName: "cache-insight"); + +var gateway = builder.AddProject("apigateway"); + +for (var i = 0; i < 5; ++i) +{ + var generationService = builder.AddProject($"generation-service-{i}", launchProfileName: null) + .WithHttpEndpoint(8000 + i) + .WithReference(cache, "RedisCache") + .WithReference(awsResources) + .WaitFor(cache) + .WaitFor(awsResources) + .WithHttpHealthCheck("/health"); + gateway + .WithReference(generationService) + .WaitFor(generationService); +} + +builder.AddProject("client") + .WaitFor(gateway); + +builder.AddProject("eventsink", launchProfileName: null) + .WithHttpEndpoint(5280) + .WithEnvironment("ASPNETCORE_ENVIRONMENT", "Development") + .WithReference(awsResources) + .WaitFor(awsResources); + +builder.UseLocalStack(localstack); + +builder.Build().Run(); diff --git a/AppHost/AppHost.AppHost/CloudFormation/event-sink-sns-localstack.yaml b/AppHost/AppHost.AppHost/CloudFormation/event-sink-sns-localstack.yaml new file mode 100644 index 00000000..13149f90 --- /dev/null +++ b/AppHost/AppHost.AppHost/CloudFormation/event-sink-sns-localstack.yaml @@ -0,0 +1,72 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: 'CloudFormation template for medical patient project' + +Parameters: + BucketName: + Type: String + Description: Name for the S3 bucket + Default: 'medical-patient-bucket' + + TopicName: + Type: String + Description: Name for the SNS topic + Default: 'medical-patient-topic' + +Resources: + MedicalPatientBucket: + Type: AWS::S3::Bucket + Properties: + BucketName: + Ref: BucketName + VersioningConfiguration: + Status: Suspended + Tags: + - Key: Name + Value: + Ref: BucketName + - Key: Environment + Value: Sample + PublicAccessBlockConfiguration: + BlockPublicAcls: true + BlockPublicPolicy: true + IgnorePublicAcls: true + RestrictPublicBuckets: true + + MedicalPatientTopic: + Type: AWS::SNS::Topic + Properties: + TopicName: + Ref: TopicName + DisplayName: + Ref: TopicName + Tags: + - Key: Name + Value: + Ref: TopicName + - Key: Environment + Value: Sample + +Outputs: + S3BucketName: + Description: Name of the S3 bucket + Value: + Ref: MedicalPatientBucket + + S3BucketArn: + Description: ARN of the S3 bucket + Value: + Fn::GetAtt: + - MedicalPatientBucket + - Arn + + SNSTopicName: + Description: Name of the SNS topic + Value: + Fn::GetAtt: + - MedicalPatientTopic + - TopicName + + SNSTopicArn: + Description: ARN of the SNS topic + Value: + Ref: MedicalPatientTopic diff --git a/AppHost/AppHost.AppHost/Properties/launchSettings.json b/AppHost/AppHost.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..8484d2c3 --- /dev/null +++ b/AppHost/AppHost.AppHost/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17103;http://localhost:15134", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21139", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23225", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22067" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15134", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19075", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18212", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20001" + } + } + } +} diff --git a/AppHost/AppHost.AppHost/appsettings.Development.json b/AppHost/AppHost.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/AppHost/AppHost.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/AppHost/AppHost.AppHost/appsettings.json b/AppHost/AppHost.AppHost/appsettings.json new file mode 100644 index 00000000..10b51f59 --- /dev/null +++ b/AppHost/AppHost.AppHost/appsettings.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "Cache": { + "CacheTime": 60 + }, + "LocalStack": { + "UseLocalStack": true + } +} \ No newline at end of file diff --git a/AppHost/AppHost.ServiceDefaults/AppHost.ServiceDefaults.csproj b/AppHost/AppHost.ServiceDefaults/AppHost.ServiceDefaults.csproj new file mode 100644 index 00000000..a80a31c3 --- /dev/null +++ b/AppHost/AppHost.ServiceDefaults/AppHost.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/AppHost/AppHost.ServiceDefaults/Extensions.cs b/AppHost/AppHost.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..f2b2c459 --- /dev/null +++ b/AppHost/AppHost.ServiceDefaults/Extensions.cs @@ -0,0 +1,105 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace AppHost.ServiceDefaults; + +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 => + { + http.AddStandardResilienceHandler(); + http.AddServiceDiscovery(); + }); + + 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 => + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + return builder; + } + + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Services.AddHealthChecks() + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + // if (app.Environment.IsDevelopment()) + // { + // app.MapHealthChecks(HealthEndpointPath); + // app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + // { + // Predicate = r => r.Tags.Contains("live") + // }); + // } + + app.MapHealthChecks("/health"); + app.MapHealthChecks("/alive", new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + + return app; + } +} diff --git a/CachingService/CachingService.csproj b/CachingService/CachingService.csproj new file mode 100644 index 00000000..0be7cdc3 --- /dev/null +++ b/CachingService/CachingService.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/CachingService/Services/CacheService.cs b/CachingService/Services/CacheService.cs new file mode 100644 index 00000000..54037bfd --- /dev/null +++ b/CachingService/Services/CacheService.cs @@ -0,0 +1,47 @@ +using Domain.Entities; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Configuration; +using System.Text.Json; + +namespace CachingService.Services; + +/// +/// Реализация сервиса кэширования с использованием распределенного кэша (Redis). +/// +public class CacheService(IDistributedCache cache, IConfiguration configuration) : ICacheService +{ + private readonly TimeSpan _cacheExpiration = + TimeSpan.FromSeconds(configuration.GetValue("Cache:CacheTime", 60)); + + /// + /// Извлекает данные пациента из кэша по идентификатору. + /// + /// Идентификатор пациента. + /// + /// Объект если найден в кэше, иначе null. + /// + public async Task RetriveFromCache(int id) + { + var cachedData = await cache.GetStringAsync(id.ToString()); + if (!string.IsNullOrEmpty(cachedData)) + { + return JsonSerializer.Deserialize(cachedData); + } + + return null; + } + + /// + /// Сохраняет данные пациента в кэш. + /// + /// Объект для сохранения. + public async Task PutInCache(MedicalPatient patient) + { + var data = JsonSerializer.Serialize(patient); + await cache.SetStringAsync(patient.Id.ToString(), data, + new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheExpiration + }); + } +} \ No newline at end of file diff --git a/CachingService/Services/ICacheService.cs b/CachingService/Services/ICacheService.cs new file mode 100644 index 00000000..863827e5 --- /dev/null +++ b/CachingService/Services/ICacheService.cs @@ -0,0 +1,21 @@ +using Domain.Entities; + +namespace CachingService.Services; + +/// +/// Интерфейс для сервиса кэширования пациентов медицинской базы данных. +/// +public interface ICacheService +{ + /// + /// Извлекает данные пациента из кэша по идентификатору. + /// + /// Идентификатор пациента. + public Task RetriveFromCache(int id); + + /// + /// Сохраняет данные пациента в кэш. + /// + /// Объект для сохранения в кэш. + public Task PutInCache(MedicalPatient patient); +} diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..810272a0 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,13 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №3 "Балансировка нагрузки" + Вариант №13 "Медицинский пациент"Доменная область + Балансировщик "Weighted Random" + Брокер "SNS" + Хостинг S3 "Localstack" + Выполнена Семыкиным Степаном 6511 + Ссылка на форк 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..d6191284 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7268/patient" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..c5c445c5 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -3,7 +3,23 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 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}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AppHost.AppHost", "AppHost\AppHost.AppHost\AppHost.AppHost.csproj", "{FA60BD7F-DF2E-43E1-8B29-FA15DAFEECCB}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AppHost.ServiceDefaults", "AppHost\AppHost.ServiceDefaults\AppHost.ServiceDefaults.csproj", "{356013C7-A662-4C23-A6EF-EB7998D1A4A0}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GenerationService", "GenerationService\GenerationService.csproj", "{E0CA55CB-CEB7-4415-B6BF-715B73DABB9B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CachingService", "CachingService\CachingService.csproj", "{50EED674-F3C9-465E-ADF7-F0591E1EB2E0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Domain", "Domain\Domain.csproj", "{E528BBC3-1C26-8C35-F682-23718816ADCD}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiGateway", "ApiGateway\ApiGateway.csproj", "{ABE66B30-BD47-A7B2-B17B-5BA67959B026}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventSink", "EventSink\EventSink.csproj", "{8CBBB1B4-7A06-3A36-B43C-7E23470FCD46}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{EA40C2FD-2BB7-4C99-91CA-389DFB28A8EC}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,6 +31,38 @@ 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 + {FA60BD7F-DF2E-43E1-8B29-FA15DAFEECCB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA60BD7F-DF2E-43E1-8B29-FA15DAFEECCB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA60BD7F-DF2E-43E1-8B29-FA15DAFEECCB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA60BD7F-DF2E-43E1-8B29-FA15DAFEECCB}.Release|Any CPU.Build.0 = Release|Any CPU + {356013C7-A662-4C23-A6EF-EB7998D1A4A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {356013C7-A662-4C23-A6EF-EB7998D1A4A0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {356013C7-A662-4C23-A6EF-EB7998D1A4A0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {356013C7-A662-4C23-A6EF-EB7998D1A4A0}.Release|Any CPU.Build.0 = Release|Any CPU + {E0CA55CB-CEB7-4415-B6BF-715B73DABB9B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E0CA55CB-CEB7-4415-B6BF-715B73DABB9B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E0CA55CB-CEB7-4415-B6BF-715B73DABB9B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E0CA55CB-CEB7-4415-B6BF-715B73DABB9B}.Release|Any CPU.Build.0 = Release|Any CPU + {50EED674-F3C9-465E-ADF7-F0591E1EB2E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {50EED674-F3C9-465E-ADF7-F0591E1EB2E0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {50EED674-F3C9-465E-ADF7-F0591E1EB2E0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {50EED674-F3C9-465E-ADF7-F0591E1EB2E0}.Release|Any CPU.Build.0 = Release|Any CPU + {E528BBC3-1C26-8C35-F682-23718816ADCD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E528BBC3-1C26-8C35-F682-23718816ADCD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E528BBC3-1C26-8C35-F682-23718816ADCD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E528BBC3-1C26-8C35-F682-23718816ADCD}.Release|Any CPU.Build.0 = Release|Any CPU + {ABE66B30-BD47-A7B2-B17B-5BA67959B026}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ABE66B30-BD47-A7B2-B17B-5BA67959B026}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ABE66B30-BD47-A7B2-B17B-5BA67959B026}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ABE66B30-BD47-A7B2-B17B-5BA67959B026}.Release|Any CPU.Build.0 = Release|Any CPU + {8CBBB1B4-7A06-3A36-B43C-7E23470FCD46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8CBBB1B4-7A06-3A36-B43C-7E23470FCD46}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8CBBB1B4-7A06-3A36-B43C-7E23470FCD46}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8CBBB1B4-7A06-3A36-B43C-7E23470FCD46}.Release|Any CPU.Build.0 = Release|Any CPU + {EA40C2FD-2BB7-4C99-91CA-389DFB28A8EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EA40C2FD-2BB7-4C99-91CA-389DFB28A8EC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EA40C2FD-2BB7-4C99-91CA-389DFB28A8EC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EA40C2FD-2BB7-4C99-91CA-389DFB28A8EC}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Domain/Domain.csproj b/Domain/Domain.csproj new file mode 100644 index 00000000..5d6e8277 --- /dev/null +++ b/Domain/Domain.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/Domain/Entities/MedicalPatient.cs b/Domain/Entities/MedicalPatient.cs new file mode 100644 index 00000000..5e9bd60e --- /dev/null +++ b/Domain/Entities/MedicalPatient.cs @@ -0,0 +1,69 @@ +using System.Text.Json.Serialization; + +namespace Domain.Entities; + +/// +/// Класс определяющий пациента в медицинской базе данных. +/// +public class MedicalPatient +{ + /// + /// Идентификатор пациента. + /// + [JsonPropertyName("id")] + public required int Id { get; set; } + + /// + /// Имя. + /// + [JsonPropertyName("name")] + public required string Name { get; set; } + + /// + /// Адрес. + /// + [JsonPropertyName("address")] + public required string Address { get; set; } + + /// + /// Дата рождения. + /// + [JsonPropertyName("birthDate")] + public required DateOnly BirthDate { get; set; } + + /// + /// Рост в метрах. + /// + [JsonPropertyName("height")] + public required double Height { get; set; } + + /// + /// Масса в килограммах. + /// + [JsonPropertyName("weight")] + public required double Weight { get; set; } + + /// + /// Группа крови. + /// + [JsonPropertyName("bloodGroup")] + public int? BloodGroup { get; set; } + + /// + /// Резус-фактор. + /// + [JsonPropertyName("rh")] + public bool? Rh { get; set; } + + /// + /// Дата последнего визита. + /// + [JsonPropertyName("lastVisit")] + public DateOnly? LastVisit { get; set; } + + /// + /// Статус вакцинации. + /// + [JsonPropertyName("vaccination")] + public bool? Vaccination { get; set; } +} diff --git a/EventSink/Controllers/StorageController.cs b/EventSink/Controllers/StorageController.cs new file mode 100644 index 00000000..14923b2a --- /dev/null +++ b/EventSink/Controllers/StorageController.cs @@ -0,0 +1,69 @@ +using EventSink.Storage; +using Microsoft.AspNetCore.Mvc; +using System.Text; +using System.Text.Json.Nodes; + +namespace EventSink.Controllers; + +/// +/// Контроллер для взаимодействия с S3. +/// +/// Служба для работы с S3. +/// Логгер для записи событий и ошибок. +[ApiController] +[Route("api/storage")] +public class StorageController(IStorageService storageService, ILogger logger) : ControllerBase +{ + /// + /// Получает список хранящихся в S3 файлов. + /// + /// Список с ключами файлов. + [HttpGet] + [ProducesResponseType(200)] + [ProducesResponseType(500)] + public async Task>> ListFiles() + { + logger.LogInformation("Method {method} of {controller} was called", nameof(ListFiles), nameof(StorageController)); + + try + { + var list = await storageService.GetFileList(); + logger.LogInformation("Got a list of {count} files from bucket", list.Count); + + return Ok(list); + } + catch (Exception ex) + { + logger.LogError(ex, "Exception occured during {method} of {controller}", nameof(ListFiles), nameof(StorageController)); + + return BadRequest(ex); + } + } + + /// + /// Получает строковое представление хранящегося в S3 документа. + /// + /// Ключ файла. + /// Строковое представление файла. + [HttpGet("{key}")] + [ProducesResponseType(200)] + [ProducesResponseType(500)] + public async Task> GetFile(string key) + { + logger.LogInformation("Method {method} of {controller} was called", nameof(GetFile), nameof(StorageController)); + + try + { + var node = await storageService.DownloadFile(key); + logger.LogInformation("Received json of {size} bytes", Encoding.UTF8.GetByteCount(node.ToJsonString())); + + return Ok(node); + } + catch (Exception ex) + { + logger.LogError(ex, "Exception occured during {method} of {controller}", nameof(GetFile), nameof(StorageController)); + + return BadRequest(ex); + } + } +} diff --git a/EventSink/Controllers/SubscriptionController.cs b/EventSink/Controllers/SubscriptionController.cs new file mode 100644 index 00000000..0d28fe86 --- /dev/null +++ b/EventSink/Controllers/SubscriptionController.cs @@ -0,0 +1,73 @@ +using Amazon.SimpleNotificationService.Util; +using EventSink.Storage; +using Microsoft.AspNetCore.Mvc; +using System.Text; + +namespace EventSink.Controllers; + +/// +/// Контроллер для обработки входящих сообщений SNS. +/// +/// Служба для загрузки данных в S3 хранилище. +/// Логгер для записи событий и ошибок. +[ApiController] +[Route("api/sns")] +public class SubscriptionController(IStorageService storageService, ILogger logger) : ControllerBase +{ + /// + /// Принимает и обрабатывает входящее сообщение (подтверждение подписки и уведомления). + /// При получении уведомления содержимое сообщения сохраняется в S3. + /// + /// Результат обработки HTTP-запроса. + [HttpPost] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task ReceiveMessage() + { + logger.LogInformation("SNS webhook was called"); + + try + { + using var reader = new StreamReader(Request.Body, Encoding.UTF8); + var jsonContent = await reader.ReadToEndAsync(); + + var snsMessage = Message.ParseMessage(jsonContent); + + if (snsMessage.Type == "SubscriptionConfirmation") + { + logger.LogInformation("SubscriptionConfirmation was received"); + + using var httpClient = new HttpClient(); + var builder = new UriBuilder(new Uri(snsMessage.SubscribeURL)) + { + Scheme = "http", + Host = "localhost", + Port = 4566 + }; + + var response = await httpClient.GetAsync(builder.Uri); + if (!response.IsSuccessStatusCode) + { + var body = await response.Content.ReadAsStringAsync(); + throw new Exception($"SubscriptionConfirmation returned {response.StatusCode}: {body}"); + } + + logger.LogInformation("Subscription was successfully confirmed"); + + return Ok(); + } + + if (snsMessage.Type == "Notification") + { + logger.LogInformation("Notification received: {message}", snsMessage.MessageText); + await storageService.UploadFile(snsMessage.MessageText); + logger.LogInformation("Notification was successfully processed"); + } + } + catch (Exception ex) + { + logger.LogError(ex, "Exception occurred while processing SNS notifications"); + } + + return Ok(); + } +} \ No newline at end of file diff --git a/EventSink/EventSink.csproj b/EventSink/EventSink.csproj new file mode 100644 index 00000000..f926efb4 --- /dev/null +++ b/EventSink/EventSink.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + + diff --git a/EventSink/Messaging/SubscriptionService.cs b/EventSink/Messaging/SubscriptionService.cs new file mode 100644 index 00000000..e5ca1da3 --- /dev/null +++ b/EventSink/Messaging/SubscriptionService.cs @@ -0,0 +1,46 @@ +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; +using System.Net; + +namespace EventSink.Messaging; + +/// +/// Служба для подписки на SNS. +/// +/// Клиент SNS. +/// Конфигурация приложения. +/// Логгер для записи событий и ошибок. +public class SubscriptionService(IAmazonSimpleNotificationService snsClient, IConfiguration configuration, ILogger logger) +{ + private readonly string _topicArn = configuration["AWS:Resources:SNSTopicArn"] + ?? throw new KeyNotFoundException("SNS topic link was not found in configuration"); + + private readonly string _endpoint = configuration["AWS:Resources:SNSUrl"] + ?? throw new KeyNotFoundException("SNS endpoint was not found in configuration"); + + /// + /// Эндпоинт для отправки запроса на подписку. + /// + public async Task SubscribeEndpoint() + { + logger.LogInformation("Sending subscribe request for {topic}", _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}", _topicArn); + } + else + { + logger.LogInformation("Subscription request for {topic} is successful, waiting for confirmation", _topicArn); + } + } +} \ No newline at end of file diff --git a/EventSink/Program.cs b/EventSink/Program.cs new file mode 100644 index 00000000..a90a16bb --- /dev/null +++ b/EventSink/Program.cs @@ -0,0 +1,39 @@ +using Amazon.S3; +using Amazon.SimpleNotificationService; +using AppHost.ServiceDefaults; +using EventSink.Messaging; +using EventSink.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(); + options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{assembly.GetName().Name}.xml")); +}); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddScoped(); +builder.Services.AddAwsService(); +builder.Services.AddAwsService(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +using var scope = app.Services.CreateScope(); + +await scope.ServiceProvider.GetRequiredService().SubscribeEndpoint(); +await scope.ServiceProvider.GetRequiredService().EnsureBucketExists(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} +app.MapControllers(); +app.Run(); diff --git a/EventSink/Properties/launchSettings.json b/EventSink/Properties/launchSettings.json new file mode 100644 index 00000000..af7b55ac --- /dev/null +++ b/EventSink/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:26997", + "sslPort": 44309 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5141", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7152;http://localhost:5141", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/EventSink/Storage/IStorageService.cs b/EventSink/Storage/IStorageService.cs new file mode 100644 index 00000000..a7de3661 --- /dev/null +++ b/EventSink/Storage/IStorageService.cs @@ -0,0 +1,33 @@ +using System.Text.Json.Nodes; + +namespace EventSink.Storage; + +/// +/// Интерфейс службы для взаимодействия с файлами в S3. +/// +public interface IStorageService +{ + /// + /// Отправляет файл в хранилище. + /// + /// Строковая репрезентация сохраняемого файла. + public Task UploadFile(string fileData); + + /// + /// Получает список всех файлов из хранилища. + /// + /// Список путей к файлам. + public Task> GetFileList(); + + /// + /// Получает строковую репрезентацию файла из хранилища. + /// + /// Путь к файлу в бакете. + /// Строковая репрезентация прочтенного файла. + public Task DownloadFile(string filePath); + + /// + /// Создает бакет. + /// + public Task EnsureBucketExists(); +} diff --git a/EventSink/Storage/StorageService.cs b/EventSink/Storage/StorageService.cs new file mode 100644 index 00000000..45fdb22f --- /dev/null +++ b/EventSink/Storage/StorageService.cs @@ -0,0 +1,137 @@ +using Amazon.S3; +using Amazon.S3.Model; +using System.Net; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace EventSink.Storage; + +/// +/// Cлужба для манипуляции файлами в S3. +/// +/// S3 клиент. +/// Конфигурация приложения. +/// Логгер для записи событий и ошибок. +public class StorageService(IAmazonS3 client, IConfiguration configuration, ILogger logger) : IStorageService +{ + private readonly string _bucketName = configuration["AWS:Resources:S3BucketName"] + ?? throw new KeyNotFoundException("S3 bucket name was not found in configuration"); + + /// + public async Task> GetFileList() + { + var list = new List(); + var request = new ListObjectsV2Request + { + BucketName = _bucketName, + Prefix = "", + Delimiter = ",", + }; + var paginator = client.Paginators.ListObjectsV2(request); + + logger.LogInformation("Began listing files in {bucket}", _bucketName); + + await foreach (var response in paginator.Responses) + if (response != null && response.S3Objects != null) + { + foreach (var obj in response.S3Objects) + { + if (obj != null) + { + list.Add(obj.Key); + } + else + { + logger.LogWarning("Received null object from {bucket}", _bucketName); + } + } + } + else + { + logger.LogWarning("Received null response from {bucket}", _bucketName); + } + + return list; + } + + /// + public async Task UploadFile(string fileData) + { + var rootNode = JsonNode.Parse(fileData) ?? throw new ArgumentException("Passed string is not a valid JSON"); + var id = rootNode["id"]?.GetValue() ?? throw new ArgumentException("Passed JSON has invalid structure"); + + using var stream = new MemoryStream(); + JsonSerializer.Serialize(stream, rootNode); + stream.Seek(0, SeekOrigin.Begin); + + logger.LogInformation("Began uploading patient {file} onto {bucket}", id, _bucketName); + + var request = new PutObjectRequest + { + BucketName = _bucketName, + Key = $"patient_{id}.json", + InputStream = stream + }; + + var response = await client.PutObjectAsync(request); + + if (response.HttpStatusCode != HttpStatusCode.OK) + { + logger.LogError("Failed to upload patient {file}: {code}", id, response.HttpStatusCode); + + return false; + } + + logger.LogInformation("Finished uploading patient {file} to {bucket}", id, _bucketName); + + return true; + } + + /// + public async Task DownloadFile(string key) + { + logger.LogInformation("Began downloading {file} from {bucket}", key, _bucketName); + + try + { + var request = new GetObjectRequest + { + BucketName = _bucketName, + Key = key + }; + using var response = await client.GetObjectAsync(request); + + if (response.HttpStatusCode != HttpStatusCode.OK) + { + logger.LogError("Failed to download {file}: {code}", key, response.HttpStatusCode); + throw new InvalidOperationException($"Error occurred downloading {key} - {response.HttpStatusCode}"); + } + using var reader = new StreamReader(response.ResponseStream, Encoding.UTF8); + + return JsonNode.Parse(reader.ReadToEnd()) ?? throw new InvalidOperationException($"Downloaded document is not a valid JSON"); + } + catch (Exception ex) + { + logger.LogError(ex, "Exception occurred during {file} downloading ", key); + throw; + } + } + + /// + public async Task EnsureBucketExists() + { + logger.LogInformation("Checking whether {bucket} exists", _bucketName); + + try + { + await client.EnsureBucketExistsAsync(_bucketName); + logger.LogInformation("{bucket} existence ensured", _bucketName); + } + catch (Exception ex) + { + logger.LogError(ex, "Unhandled exception occurred during {bucket} check", _bucketName); + throw; + } + } +} diff --git a/EventSink/appsettings.Development.json b/EventSink/appsettings.Development.json new file mode 100644 index 00000000..770d3e93 --- /dev/null +++ b/EventSink/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "DetailedErrors": true, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/EventSink/appsettings.json b/EventSink/appsettings.json new file mode 100644 index 00000000..538c4fde --- /dev/null +++ b/EventSink/appsettings.json @@ -0,0 +1,18 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Settings": { + "MessageBroker": "SNS", + "S3Hosting": "Localstack" + }, + "AWS": { + "Resources": { + "SNSUrl": "http://host.docker.internal:5280/api/sns" + } + } +} \ No newline at end of file diff --git a/GenerationService/GenerationService.csproj b/GenerationService/GenerationService.csproj new file mode 100644 index 00000000..a104c0ff --- /dev/null +++ b/GenerationService/GenerationService.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + + diff --git a/GenerationService/Messaging/IProductionService.cs b/GenerationService/Messaging/IProductionService.cs new file mode 100644 index 00000000..46cf6f26 --- /dev/null +++ b/GenerationService/Messaging/IProductionService.cs @@ -0,0 +1,15 @@ +using Domain.Entities; + +namespace GenerationService.Messaging; + +/// +/// Интерфейс для службы публикации сообщений. +/// +public interface IProductionService +{ + /// + /// Публикует сообщение с данными. + /// + /// Данные медицинского пациента для публикации. + public Task SendMessage(MedicalPatient patient); +} diff --git a/GenerationService/Messaging/PublicationService.cs b/GenerationService/Messaging/PublicationService.cs new file mode 100644 index 00000000..e7613083 --- /dev/null +++ b/GenerationService/Messaging/PublicationService.cs @@ -0,0 +1,48 @@ +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; +using Domain.Entities; +using System.Net; +using System.Text.Json; + +namespace GenerationService.Messaging; + +/// +/// Сервис для публикации сообщений в SNS. +/// +/// Клиент SNS. +/// Конфигурация приложерния. +/// Логгер для записи событий и ошибок. +public class PublicationService(IAmazonSimpleNotificationService client, IConfiguration configuration, ILogger logger) : IProductionService +{ + private readonly string _topicArn = configuration["AWS:Resources:SNSTopicArn"] + ?? throw new InvalidOperationException("AWS:Resources:SNSTopicArn is not configured"); + + /// + public async Task SendMessage(MedicalPatient patient) + { + try + { + var json = JsonSerializer.Serialize(patient); + var request = new PublishRequest + { + Message = json, + TopicArn = _topicArn + }; + + var response = await client.PublishAsync(request); + + if (response.HttpStatusCode == HttpStatusCode.OK) + { + logger.LogInformation("Patient {Id} was published to SNS", patient.Id); + } + else + { + throw new Exception($"SNS publish returned {response.HttpStatusCode}"); + } + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to publish patient {Id} to SNS", patient.Id); + } + } +} diff --git a/GenerationService/Program.cs b/GenerationService/Program.cs new file mode 100644 index 00000000..cf6d3282 --- /dev/null +++ b/GenerationService/Program.cs @@ -0,0 +1,24 @@ +using Amazon.SimpleNotificationService; +using AppHost.ServiceDefaults; +using CachingService.Services; +using GenerationService.Messaging; +using GenerationService.Services; +using LocalStack.Client.Extensions; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("RedisCache"); + +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddScoped(); +builder.Services.AddAwsService(); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); +app.MapGet("/patient", (IGeneratorService service, int id) => service.GenerateAsync(id)); + +app.Run(); diff --git a/GenerationService/Properties/launchSettings.json b/GenerationService/Properties/launchSettings.json new file mode 100644 index 00000000..349e1c89 --- /dev/null +++ b/GenerationService/Properties/launchSettings.json @@ -0,0 +1,12 @@ +{ + "profiles": { + "GenerationService": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "https://localhost:5289;http://localhost:5290" + } + } +} \ No newline at end of file diff --git a/GenerationService/Services/Generator.cs b/GenerationService/Services/Generator.cs new file mode 100644 index 00000000..119329f5 --- /dev/null +++ b/GenerationService/Services/Generator.cs @@ -0,0 +1,107 @@ +using Bogus; +using Domain.Entities; + +namespace GenerationService.Services; + +/// +/// Статический генератор тестовых данных для пациентов медицинской базы данных. +/// +public static class Generator +{ + private const double MinAdultHeight = 1.50; + private const double MaxAdultHeight = 2.20; + private const int BloodGroupCount = 4; + private const int MaxAge = 120; + private const int MinBmi = 18; + private const int MaxBmi = 30; + + private const int DigitsRound = 2; + + private static readonly Faker _faker = new Faker("en") + .RuleFor(m => m.Name, f => $"{f.Name.FirstName()} {f.Name.LastName()}") + .RuleFor(m => m.Address, f => f.Address.FullAddress()) + .RuleFor(m => m.BirthDate, f => f.Date.PastDateOnly(MaxAge)) + .RuleFor(m => m.Height, (f, m) => GenerateHeightByAge(m.BirthDate, f)) + .RuleFor(m => m.Weight, (f, m) => GenerateWeightByHeight(m.Height, f)) + .RuleFor(m => m.BloodGroup, f => f.Random.Int(1, BloodGroupCount)) + .RuleFor(m => m.Rh, f => f.Random.Bool()) + .RuleFor(m => m.LastVisit, (f, m) => f.Date.BetweenDateOnly(m.BirthDate, DateOnly.FromDateTime(DateTime.Now))) + .RuleFor(m => m.Vaccination, f => f.Random.Bool()); + + /// + /// Определяет диапазон роста на основе возраста. + /// + /// Возраст пациента в годах. + /// Минимальный и максимальный рост для данного возраста. + private static (double Min, double Max) GetHeightRangeByAge(double age) + { + return age switch + { + < 1 => (0.35, 0.80), + < 3 => (0.80, 1.00), + < 7 => (1.00, 1.30), + < 13 => (1.30, 1.60), + < 18 => (1.60, 1.90), + _ => (MinAdultHeight, MaxAdultHeight) + }; + } + + /// + /// Генерирует рост пациента на основе возраста. + /// + /// Дата рождения пациента. + /// Генератор случайных данных. + /// Рост пациента в метрах. + private static double GenerateHeightByAge(DateOnly birthDate, Faker faker) + { + var age = CalculateAge(birthDate); + var (minHeight, maxHeight) = GetHeightRangeByAge(age); + + return Math.Round(faker.Random.Double(minHeight, maxHeight), DigitsRound); + } + + /// + /// Генерирует массу пациента на основе роста через индекс массы тела. + /// + /// Рост пациента в метрах. + /// Генератор случайных данных. + /// Масса пациента в килограммах. + private static double GenerateWeightByHeight(double height, Faker faker) + { + var bmi = faker.Random.Double(MinBmi, MaxBmi); + + return (int)(bmi * height * height); + } + + /// + /// Вычисляет возраст пациента на основе его даты рождения и текущей даты. + /// Учитывает случаи, когда день рождения еще не наступил в текущем году. + /// + /// Дата рождения пациента. + /// Возраст пациента в годах. + private static int CalculateAge(DateOnly birthDate) + { + var today = DateOnly.FromDateTime(DateTime.Now); + var age = today.Year - birthDate.Year; + + if (birthDate > today.AddYears(-age)) + { + age--; + } + + return age; + } + + /// + /// Генерирует случайного пациента с указанным идентификатором. + /// + /// Идентификатор пациента. + /// Сгенерированный объект с заполненными полями. + public static MedicalPatient Generate(int id) + { + var patient = _faker.Generate(); + patient.Id = id; + + return patient; + } +} diff --git a/GenerationService/Services/GeneratorService.cs b/GenerationService/Services/GeneratorService.cs new file mode 100644 index 00000000..ba091138 --- /dev/null +++ b/GenerationService/Services/GeneratorService.cs @@ -0,0 +1,74 @@ +using CachingService.Services; +using Domain.Entities; +using GenerationService.Messaging; + +namespace GenerationService.Services; + +/// +/// Сервис для генерации данных пациентов с поддержкой кэширования. +/// +/// Сервис для работы с кэшем Redis. +/// Сервис для публикации сообщений в брокер. +/// Логгер для записи событий и ошибок. +public class GeneratorService(ICacheService cacheService, IProductionService productionService, ILogger logger) : IGeneratorService +{ + /// + /// Обрабатывает запрос на генерацию данных пациента с указанным идентификатором. + /// Cначала проверяет наличие данных в кэше, если данных нет - генерирует новые и сохраняет в кэш. + /// Публикует сообщение в брокер. + /// + /// Идентификатор пациента. + /// Сгенерированный объект с заполненными полями. + public async Task GenerateAsync(int id) + { + MedicalPatient? cachedPatient = null; + try + { + cachedPatient = await cacheService.RetriveFromCache(id); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Cache read failed for Id {Id}.", id); + } + + if (cachedPatient is not null) + { + logger.LogInformation("Patient with Id {Id} retrieved from cache.", id); + + return cachedPatient; + } + + MedicalPatient patient; + try + { + patient = Generator.Generate(id); + logger.LogInformation("Patient with Id {Id} generated.", id); + } + catch (Exception ex) + { + logger.LogError(ex, "Patient generation failed for Id {Id}", id); + throw; + } + + try + { + await cacheService.PutInCache(patient); + logger.LogInformation("Patient with Id {Id} stored in cache.", id); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Cache write failed for Id {Id}", id); + } + + try + { + await productionService.SendMessage(patient); + } + catch (Exception ex) + { + logger.LogWarning(ex, "SNS publish failed for Id {Id}", id); + } + + return patient; + } +} diff --git a/GenerationService/Services/IGeneratorService.cs b/GenerationService/Services/IGeneratorService.cs new file mode 100644 index 00000000..0af399bd --- /dev/null +++ b/GenerationService/Services/IGeneratorService.cs @@ -0,0 +1,16 @@ +using Domain.Entities; + +namespace GenerationService.Services; + +/// +/// Интерфейс для генератора тестовых данных пациентов медицинской базы данных. +/// +public interface IGeneratorService +{ + /// + /// Обрабатывает запрос на генерацию данных пациента с указанным идентификатором. + /// + /// Идентификатор пациента. + /// Сгенерированный объект с заполненными полями. + public Task GenerateAsync(int id); +} diff --git a/GenerationService/appsettings.Development.json b/GenerationService/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/GenerationService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/GenerationService/appsettings.json b/GenerationService/appsettings.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/GenerationService/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/README.md b/README.md index dcaa5eb7..998b9832 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,77 @@ # Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing) +### Вариант 13 Медицинский пациент -## Задание -### Цель -Реализация проекта микросервисного бекенда. - -### Задачи -* Реализация межсервисной коммуникации, -* Изучение работы с брокерами сообщений, -* Изучение архитектурных паттернов, -* Изучение работы со средствами оркестрации на примере .NET Aspire, -* Повторение основ работы с системами контроля версий, -* Интеграционное тестирование. - -### Лабораторные работы +### Лабораторная работа №1
1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов
- В рамках первой лабораторной работы необходимо: * Реализовать сервис генерации контрактов на основе Bogus, * Реализовать кеширование при помощи IDistributedCache и Redis, * Реализовать структурное логирование сервиса генерации, * Настроить оркестрацию Aspire. - +
+ +Реализовано: +1. Доменная модель: *Domain* +2. Сервис генерации данных пациента с заданным идентификатором: *GenerationService* +3. Сервис кэширования Redis: *CachingService* +4. Сервис оркестрации Aspire: *AppHost.AppHost* +5. Сервис телеметрии OpenTelemetry: *AppHost.ServiceDefaults* + +Примеры интерфейса: + +![1](https://github.com/user-attachments/assets/bc050486-c80b-4a8b-87e2-6fd0b510a68f) + +![2](https://github.com/user-attachments/assets/c8bdd235-9656-476f-ae93-f8a9e7a75bd2) + +![3](https://github.com/user-attachments/assets/bb429a0c-7553-4c5c-b863-4bacf5c5b67a) + +### Лабораторная работа №2
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы -
- +2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы +
В рамках второй лабораторной работы необходимо: * Настроить оркестрацию на запуск нескольких реплик сервиса генерации, * Реализовать апи гейтвей на основе Ocelot, * Имплементировать алгоритм балансировки нагрузки согласно варианту. -
+ +Реализовано: +1. ApiGateway: *ApiGateway* +2. Балансировщик нагрузки WeightedRandomBalancer: *ApiGateway/LoadBalancer* + +Примеры интерфейса: + +![4](https://github.com/user-attachments/assets/469da2a1-2431-4faa-9e25-0cb7596a3352) + +![5](https://github.com/user-attachments/assets/26bbde9a-8b7c-458b-9835-b1a933d47df5) + +### Лабораторная работа №3
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. Полнота выполнения задания +Реализовано: +1. Брокер сообщений SNS: +2. Файловый сервис с объектным хранилищем Amazon S3 и хостингом через Localstack: *EventSink* +3. 5 интеграционныз тестов: *Tests* -Быстрее делаете PR - у вас преимущество. -Быстрее получаете Approve - у вас преимущество. -Выполните нечто немного выходящее за рамки проекта - у вас преимущество. -Не укладываетесь в дедлайн - получаете минимально возможный балл. +Примеры интерфейса: -### Шкала оценивания +![6](https://github.com/user-attachments/assets/11238dd1-50b3-4f71-a931-0df4a7c9a3bb) -- **3 балла** за качество кода, из них: - - 2 балла - базовая оценка - - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов: - - Реализация факультативного функционала - - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл - -## Вопросы и обратная связь по курсу +![7](https://github.com/user-attachments/assets/64dd9dcb-a319-4b67-9a72-04dacd444bf3) -Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](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). +![8](https://github.com/user-attachments/assets/0bf0f514-5491-422f-a9c9-73b5e490a796) +![9](https://github.com/user-attachments/assets/467819d6-7533-4fd4-adf5-764949914e10) diff --git a/Tests/Fixture.cs b/Tests/Fixture.cs new file mode 100644 index 00000000..17427630 --- /dev/null +++ b/Tests/Fixture.cs @@ -0,0 +1,118 @@ +using Amazon.S3; +using Amazon.S3.Model; +using Aspire.Hosting; + +namespace Tests; + +/// +/// Подготавливает окружение для интеграционных тестов: поднимает локальные ресурсы, предоставляет S3 клиент, ожидает инициализации. +/// +public class Fixture : IAsyncLifetime +{ + private const string BucketName = "medical-patient-bucket"; + + public DistributedApplication App { get; private set; } = null!; + public IDistributedApplicationTestingBuilder Builder { get; private set; } = null!; + public AmazonS3Client StorageClient { get; private set; } = null!; + + /// + /// Инициализация фикстуры: создание билдера, запуск приложения и подготовка S3. + /// + public async Task InitializeAsync() + { + Builder = await DistributedApplicationTestingBuilder.CreateAsync(); + Builder.Configuration["DcpPublisher:RandomizePorts"] = "false"; + + Builder.Services.ConfigureHttpClientDefaults(http => + http.AddStandardResilienceHandler(options => + { + options.TotalRequestTimeout.Timeout = TimeSpan.FromMinutes(3); + options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(60); + options.CircuitBreaker.SamplingDuration = TimeSpan.FromMinutes(3); + options.Retry.MaxRetryAttempts = 10; + options.Retry.Delay = TimeSpan.FromSeconds(3); + })); + + App = await Builder.BuildAsync(); + await App.StartAsync(); + + using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(3)); + + await Task.WhenAll( + App.ResourceNotifications.WaitForResourceHealthyAsync("localstack", cts.Token), + App.ResourceNotifications.WaitForResourceHealthyAsync("apigateway", cts.Token), + App.ResourceNotifications.WaitForResourceHealthyAsync("eventsink", cts.Token) + ); + + var localStackUrl = App.GetEndpoint("localstack", "http").ToString().TrimEnd('/'); + StorageClient = new AmazonS3Client("test", "test", new AmazonS3Config + { + ServiceURL = localStackUrl, + ForcePathStyle = true + }); + + await EnsureBucketExistsAsync(cts.Token); + } + + /// + /// Ожидает появления объектов в S3 с указанным префиксом. + /// + /// Префикс ключа объекта в бакете. + /// Максимальное число попыток проверки. + /// Токен отмены операции. + /// Список найденных объектов S3. + public async Task> WaitForObjectAsync(string prefix, int maxAttempts = 10, CancellationToken cancellationToken = default) + { + for (var i = 0; i < maxAttempts; i++) + { + cancellationToken.ThrowIfCancellationRequested(); + + await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken); + + var listResponse = await StorageClient.ListObjectsV2Async(new ListObjectsV2Request + { + BucketName = BucketName, + Prefix = prefix + }, cancellationToken); + + if (listResponse.S3Objects.Count > 0) + { + return listResponse.S3Objects; + } + } + + return []; + } + + /// + /// Создаёт бакет в S3, если он не существует. + /// + /// Токен отмены операции. + private async Task EnsureBucketExistsAsync(CancellationToken cancellationToken) + { + var buckets = await StorageClient.ListBucketsAsync(cancellationToken); + + if (buckets.Buckets.Exists(b => b.BucketName == BucketName)) + { + return; + } + + await StorageClient.PutBucketAsync(new PutBucketRequest + { + BucketName = BucketName, + UseClientRegion = true + }, cancellationToken); + } + + /// + /// Останавливает тесты и освобождаяет ресурсы. + /// + public async Task DisposeAsync() + { + StorageClient.Dispose(); + + await App!.StopAsync(); + await App.DisposeAsync(); + await Builder!.DisposeAsync(); + } +} diff --git a/Tests/IntegrationTests.cs b/Tests/IntegrationTests.cs new file mode 100644 index 00000000..63530191 --- /dev/null +++ b/Tests/IntegrationTests.cs @@ -0,0 +1,150 @@ +using Domain.Entities; +using System.Text.Json; + +namespace Tests; + +/// +/// Проводит интеграционные тесты. +/// +public class IntegrationTests(Fixture fixture) : IClassFixture +{ + private static readonly Random _random = new(); + + /// + /// Проверяет полный пайплайн: генерация пациента, публикация в SNS, сохранение в S3. + /// + [Fact] + public async Task Pipeline() + { + var id = _random.Next(1, 100); + + using var gatewayClient = fixture.App.CreateHttpClient("apigateway", "http"); + using var gatewayResponse = await gatewayClient.GetAsync($"/patient?id={id}"); + var patient = JsonSerializer.Deserialize( + await gatewayResponse.Content.ReadAsStringAsync()); + + var storageObjects = await fixture.WaitForObjectAsync($"patient_{id}.json"); + + using var sinkClient = fixture.App.CreateHttpClient("eventsink", "http"); + using var listResponse = await sinkClient.GetAsync("/api/storage"); + var fileList = JsonSerializer.Deserialize>( + await listResponse.Content.ReadAsStringAsync()); + + using var storageResponse = await sinkClient.GetAsync($"/api/storage/patient_{id}.json"); + var storagePatient = JsonSerializer.Deserialize( + await storageResponse.Content.ReadAsStringAsync()); + + Assert.NotEmpty(storageObjects); + Assert.NotNull(fileList); + Assert.Contains($"patient_{id}.json", fileList); + Assert.NotNull(patient); + Assert.NotNull(storagePatient); + Assert.Equal(id, storagePatient.Id); + Assert.Equivalent(patient, storagePatient); + } + + /// + /// Проверяет что Api Gateway возвращает 200. + /// + [Fact] + public async Task Gateway() + { + var id = _random.Next(1, 100); + + using var gatewayClient = fixture.App.CreateHttpClient("apigateway", "http"); + using var response = await gatewayClient.GetAsync($"/patient?id={id}"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Проверяет что данные пациентов сохраняются корректно. + /// + [Fact] + public async Task MultiplePatients() + { + var ids = Enumerable.Range(1, 3).Select(_ => _random.Next(100, 200)).ToList(); + + using var gatewayClient = fixture.App.CreateHttpClient("apigateway", "http"); + foreach (var id in ids) + await gatewayClient.GetAsync($"/patient?id={id}"); + + foreach (var id in ids) + await fixture.WaitForObjectAsync($"patient_{id}.json"); + + using var sinkClient = fixture.App.CreateHttpClient("eventsink", "http"); + using var listResponse = await sinkClient.GetAsync("/api/storage"); + var fileList = JsonSerializer.Deserialize>( + await listResponse.Content.ReadAsStringAsync()); + + Assert.NotNull(fileList); + foreach (var id in ids) + Assert.Contains($"patient_{id}.json", fileList); + } + + /// + /// Проверяет что список файлов в S3 не пустой после генерации. + /// + [Fact] + public async Task FileList() + { + var id = _random.Next(200, 300); + + using var gatewayClient = fixture.App.CreateHttpClient("apigateway", "http"); + await gatewayClient.GetAsync($"/patient?id={id}"); + await fixture.WaitForObjectAsync($"patient_{id}.json"); + + using var sinkClient = fixture.App.CreateHttpClient("eventsink", "http"); + using var listResponse = await sinkClient.GetAsync("/api/storage"); + var fileList = JsonSerializer.Deserialize>( + await listResponse.Content.ReadAsStringAsync()); + + Assert.NotNull(fileList); + Assert.NotEmpty(fileList); + } + + /// + /// Проверяет что файл скачивается и десериализуется корректно. + /// + [Fact] + public async Task DownloadingFile() + { + var id = _random.Next(300, 400); + + using var gatewayClient = fixture.App.CreateHttpClient("apigateway", "http"); + await gatewayClient.GetAsync($"/patient?id={id}"); + await fixture.WaitForObjectAsync($"patient_{id}.json"); + + using var sinkClient = fixture.App.CreateHttpClient("eventsink", "http"); + using var storageResponse = await sinkClient.GetAsync($"/api/storage/patient_{id}.json"); + var patient = JsonSerializer.Deserialize( + await storageResponse.Content.ReadAsStringAsync()); + + Assert.NotNull(patient); + Assert.Equal(id, patient.Id); + Assert.False(string.IsNullOrEmpty(patient.Name)); + Assert.False(string.IsNullOrEmpty(patient.Address)); + } + + /// + /// Проверяет что повторный запрос того же id возвращает верного пациента. + /// + [Fact] + public async Task RetrieveFromCache() + { + var id = _random.Next(400, 500); + + using var gatewayClient = fixture.App.CreateHttpClient("apigateway", "http"); + using var firstResponse = await gatewayClient.GetAsync($"/patient?id={id}"); + var firstPatient = JsonSerializer.Deserialize( + await firstResponse.Content.ReadAsStringAsync()); + + using var secondResponse = await gatewayClient.GetAsync($"/patient?id={id}"); + var secondPatient = JsonSerializer.Deserialize( + await secondResponse.Content.ReadAsStringAsync()); + + Assert.NotNull(firstPatient); + Assert.NotNull(secondPatient); + Assert.Equivalent(firstPatient, secondPatient); + } +} diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj new file mode 100644 index 00000000..b1fcbb33 --- /dev/null +++ b/Tests/Tests.csproj @@ -0,0 +1,35 @@ + + + + net8.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + + + + + + + + + + +