diff --git a/Api.Gateway/Api.Gateway.csproj b/Api.Gateway/Api.Gateway.csproj new file mode 100644 index 00000000..23e8e8cf --- /dev/null +++ b/Api.Gateway/Api.Gateway.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + + + + + + + + + diff --git a/Api.Gateway/LoadBalancer/WeightedRandom.cs b/Api.Gateway/LoadBalancer/WeightedRandom.cs new file mode 100644 index 00000000..6f45c81f --- /dev/null +++ b/Api.Gateway/LoadBalancer/WeightedRandom.cs @@ -0,0 +1,50 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace Api.Gateway.LoadBalancer; + +/// +/// Балансировка случайным образом с весами +/// +public class WeightedRandom : ILoadBalancer +{ + private readonly Func>> _services = null!; + private static readonly object _locker = new(); + private readonly int[] _values = null!; + public string Type => nameof(WeightedRandom); + + public WeightedRandom(Func>> services, IConfiguration configuration) + { + _services = services; + var section = configuration.GetSection("LoadBalancer:WeightedRandom:Weights"); + + if (!section.Exists()) + { + throw new InvalidOperationException( + $"Required configuration section '{section.Path}' was not found. " + + "Please check your appsettings.json or environment variables."); + } + + var frequencies = section.Get(); + if (frequencies == null || frequencies.Length == 0) + { + throw new InvalidOperationException( + $"Configuration section '{section.Path}' exists but contains no values."); + } + _values = [.. Enumerable.Range(0, frequencies.Length).Zip(frequencies, (val, freq) => Enumerable.Repeat(val, freq)) + .SelectMany(x => x)]; + } + + public async Task> LeaseAsync(HttpContext httpContext) + { + var services = await _services.Invoke(); + lock (_locker) + { + Random.Shared.Shuffle(_values); + return new OkResponse(services[_values.First()].HostAndPort); + } + } + + public void Release(ServiceHostAndPort hostAndPort) { } +} \ No newline at end of file diff --git a/Api.Gateway/Program.cs b/Api.Gateway/Program.cs new file mode 100644 index 00000000..b9ebb6b3 --- /dev/null +++ b/Api.Gateway/Program.cs @@ -0,0 +1,33 @@ +using Api.Gateway.LoadBalancer; +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((serviceProvider, _, discoveryProvider) => + { + var configuration = serviceProvider.GetRequiredService(); + return new WeightedRandom(discoveryProvider.GetAsync, configuration); + }); + +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + { + policy.WithOrigins( + "https://localhost:5127", + "http://localhost:5127", + "https://localhost:7282" + ) + .WithMethods("GET") + .AllowAnyHeader(); + }); +}); +var app = builder.Build(); +app.UseCors(); +await app.UseOcelot(); +app.Run(); \ No newline at end of file diff --git a/Api.Gateway/Properties/launchSettings.json b/Api.Gateway/Properties/launchSettings.json new file mode 100644 index 00000000..616bee86 --- /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:54707", + "sslPort": 44338 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5124", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7185;http://localhost:5124", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} 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..54928ab1 --- /dev/null +++ b/Api.Gateway/appsettings.json @@ -0,0 +1,14 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "LoadBalancer": { + "WeightedRandom": { + "Weights": [1, 2, 3, 2, 1] + } + } +} diff --git a/Api.Gateway/ocelot.json b/Api.Gateway/ocelot.json new file mode 100644 index 00000000..958e88b8 --- /dev/null +++ b/Api.Gateway/ocelot.json @@ -0,0 +1,23 @@ +{ + "Routes": [ + { + "UpstreamPathTemplate": "/training-course", + "UpstreamHttpMethod": [ "GET" ], + "DownstreamPathTemplate": "/training-course", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { "Host": "localhost", "Port": 4000 }, + { "Host": "localhost", "Port": 4001 }, + { "Host": "localhost", "Port": 4002 }, + { "Host": "localhost", "Port": 4003 }, + { "Host": "localhost", "Port": 4004 } + ], + "LoadBalancerOptions": { + "Type": "WeightedRandom" + } + } + ], + "GlobalConfiguration": { + "BaseUrl": "http://localhost:7185" + } +} \ No newline at end of file diff --git a/AspireApp/AspireApp.AppHost.Tests/AspireApp.AppHost.Tests.csproj b/AspireApp/AspireApp.AppHost.Tests/AspireApp.AppHost.Tests.csproj new file mode 100644 index 00000000..c1833ab9 --- /dev/null +++ b/AspireApp/AspireApp.AppHost.Tests/AspireApp.AppHost.Tests.csproj @@ -0,0 +1,33 @@ + + + + net8.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AspireApp/AspireApp.AppHost.Tests/IntegrationTest.cs b/AspireApp/AspireApp.AppHost.Tests/IntegrationTest.cs new file mode 100644 index 00000000..b3df94a1 --- /dev/null +++ b/AspireApp/AspireApp.AppHost.Tests/IntegrationTest.cs @@ -0,0 +1,93 @@ +using Aspire.Hosting; +using Microsoft.Extensions.Logging; +using Service.Api.Entities; +using System.Text.Json; +using Xunit.Abstractions; + +namespace AspireApp.AppHost.Tests; + +/// +/// Интеграционные тесты для проверки совместной работы сервисов бекенда +/// +/// Служба журналирования юнит-тестов +public class IntegrationTest(ITestOutputHelper output) : IAsyncLifetime +{ + private DistributedApplication? _app; + + /// + public async Task InitializeAsync() + { + var cancellationToken = CancellationToken.None; + IDistributedApplicationTestingBuilder builder = await DistributedApplicationTestingBuilder.CreateAsync(cancellationToken); + builder.Configuration["DcpPublisher:RandomizePorts"] = "false"; + builder.Services.AddLogging(logging => + { + logging.AddXUnit(output); + logging.SetMinimumLevel(LogLevel.Debug); + logging.AddFilter("Aspire.Hosting.Dcp", LogLevel.Debug); + logging.AddFilter("Aspire.Hosting", LogLevel.Debug); + }); + _app = await builder.BuildAsync(cancellationToken); + await _app.StartAsync(cancellationToken); + } + + /// + /// Проверяет, что вызов гейтвея возвращает сгенерированный учебный курс + /// и тот же курс через брокер попадает в Minio в виде файла + /// + [Fact] + public async Task TestPipeline_CourseIsReturnedAndStoredInMinio() + { + var random = new Random(); + var id = random.Next(1, 1000); + + using var gatewayClient = _app!.CreateHttpClient("api-gateway", "http"); + using var gatewayResponse = await gatewayClient.GetAsync($"/training-course?id={id}"); + var apiCourse = JsonSerializer.Deserialize(await gatewayResponse.Content.ReadAsStringAsync()); + + await Task.Delay(5000); + + using var fileServiceClient = _app!.CreateHttpClient("file-service", "http"); + using var listResponse = await fileServiceClient.GetAsync("/api/s3"); + var fileList = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync()); + + using var fileResponse = await fileServiceClient.GetAsync($"/api/s3/training_course_{id}.json"); + var storedCourse = JsonSerializer.Deserialize(await fileResponse.Content.ReadAsStringAsync()); + + Assert.NotNull(fileList); + Assert.NotNull(apiCourse); + Assert.NotNull(storedCourse); + Assert.Equal(id, storedCourse.Id); + Assert.Equivalent(apiCourse, storedCourse); + } + + /// + /// Проверяет, что повторный запрос того же курса возвращает идентичный результат + /// + [Fact] + public async Task TestPipeline_RepeatedRequestReturnsCachedCourse() + { + var random = new Random(); + var id = random.Next(1001, 2000); + + using var gatewayClient = _app!.CreateHttpClient("api-gateway", "http"); + + using var firstResponse = await gatewayClient.GetAsync($"/training-course?id={id}"); + var firstCourse = JsonSerializer.Deserialize(await firstResponse.Content.ReadAsStringAsync()); + + using var secondResponse = await gatewayClient.GetAsync($"/training-course?id={id}"); + var secondCourse = JsonSerializer.Deserialize(await secondResponse.Content.ReadAsStringAsync()); + + Assert.NotNull(firstCourse); + Assert.NotNull(secondCourse); + Assert.Equal(id, firstCourse.Id); + Assert.Equivalent(firstCourse, secondCourse); + } + + /// + public async Task DisposeAsync() + { + await _app!.StopAsync(); + await _app.DisposeAsync(); + } +} diff --git a/AspireApp/AspireApp.AppHost/AspireApp.AppHost.csproj b/AspireApp/AspireApp.AppHost/AspireApp.AppHost.csproj new file mode 100644 index 00000000..33832d97 --- /dev/null +++ b/AspireApp/AspireApp.AppHost/AspireApp.AppHost.csproj @@ -0,0 +1,34 @@ + + + + + + Exe + net8.0 + enable + enable + true + 3cec140f-e46f-4c50-ade0-6bd5134c5831 + + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/AspireApp/AspireApp.AppHost/CloudFormation/training-course-template.yaml b/AspireApp/AspireApp.AppHost/CloudFormation/training-course-template.yaml new file mode 100644 index 00000000..ef4d5485 --- /dev/null +++ b/AspireApp/AspireApp.AppHost/CloudFormation/training-course-template.yaml @@ -0,0 +1,29 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: 'Cloud formation template for training course project (SNS + Minio variant)' + +Parameters: + TopicName: + Type: String + Description: Name for the SNS topic + Default: 'training-course-topic' + +Resources: + TrainingCourseTopic: + Type: AWS::SNS::Topic + Properties: + TopicName: !Ref TopicName + DisplayName: !Ref TopicName + Tags: + - Key: Name + Value: !Ref TopicName + - Key: Environment + Value: Sample + +Outputs: + SNSTopicName: + Description: Name of the SNS topic + Value: !GetAtt TrainingCourseTopic.TopicName + + SNSTopicArn: + Description: ARN of the SNS topic + Value: !Ref TrainingCourseTopic diff --git a/AspireApp/AspireApp.AppHost/Program.cs b/AspireApp/AspireApp.AppHost/Program.cs new file mode 100644 index 00000000..e69928ca --- /dev/null +++ b/AspireApp/AspireApp.AppHost/Program.cs @@ -0,0 +1,57 @@ +using Amazon; +using Aspire.Hosting.LocalStack.Container; + +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("course-cache") + .WithImageTag("latest") + .WithRedisInsight(containerName: "course-insight"); + +var gateway = builder.AddProject("api-gateway"); + +var awsConfig = builder.AddAWSSDKConfig() + .WithProfile("default") + .WithRegion(RegionEndpoint.EUCentral1); + +var localstack = builder + .AddLocalStack("course-localstack", awsConfig: awsConfig, configureContainer: container => + { + container.Lifetime = ContainerLifetime.Session; + container.DebugLevel = 1; + container.LogLevel = LocalStackLogLevel.Debug; + container.Port = 4566; + container.AdditionalEnvironmentVariables.Add("DEBUG", "1"); + container.AdditionalEnvironmentVariables.Add("SNS_CERT_URL_HOST", "sns.eu-central-1.amazonaws.com"); + }); + +var awsResources = builder.AddAWSCloudFormationTemplate("resources", "CloudFormation/training-course-template.yaml", "training-course") + .WithReference(awsConfig); + +var minio = builder.AddMinioContainer("course-minio"); + +for (var i = 0; i < 5; i++) +{ + var service = builder.AddProject($"training-course-api-{i + 1}", launchProfileName: null) + .WithHttpEndpoint(4000 + i) + .WithReference(cache, "RedisCache") + .WithReference(awsResources) + .WaitFor(cache) + .WaitFor(awsResources); + gateway.WaitFor(service); +} + +builder.AddProject("training-course") + .WaitFor(gateway); + +builder.AddProject("file-service", launchProfileName: null) + .WithHttpEndpoint(5280) + .WithReference(awsResources) + .WithReference(minio) + .WithEnvironment("AWS__Resources__MinioBucketName", "training-course-bucket") + .WithEnvironment("AWS__Resources__SNSUrl", $"http://host.docker.internal:5280/api/sns") + .WaitFor(awsResources) + .WaitFor(minio); + +builder.UseLocalStack(localstack); + +builder.Build().Run(); diff --git a/AspireApp/AspireApp.AppHost/Properties/launchSettings.json b/AspireApp/AspireApp.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..d6134b49 --- /dev/null +++ b/AspireApp/AspireApp.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:17145;http://localhost:15026", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21138", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22278" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15026", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19066", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20044" + } + } + } +} diff --git a/AspireApp/AspireApp.AppHost/appsettings.Development.json b/AspireApp/AspireApp.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/AspireApp/AspireApp.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/AspireApp/AspireApp.AppHost/appsettings.json b/AspireApp/AspireApp.AppHost/appsettings.json new file mode 100644 index 00000000..d255870b --- /dev/null +++ b/AspireApp/AspireApp.AppHost/appsettings.json @@ -0,0 +1,23 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "LocalStack": { + "UseLocalStack": true, + "Session": { + "RegionName": "eu-central-1", + "AwsAccessKeyId": "test", + "AwsAccessKey": "test" + }, + "Config": { + "LocalStackHost": "localhost", + "UseSsl": false, + "UseLegacyPorts": false, + "EdgePort": 4566 + } + } +} diff --git a/AspireApp/AspireApp.ServiceDefaults/AspireApp.ServiceDefaults.csproj b/AspireApp/AspireApp.ServiceDefaults/AspireApp.ServiceDefaults.csproj new file mode 100644 index 00000000..da24936e --- /dev/null +++ b/AspireApp/AspireApp.ServiceDefaults/AspireApp.ServiceDefaults.csproj @@ -0,0 +1,26 @@ + + + + net8.0 + enable + enable + true + + + + NU1603 + + + + + + + + + + + + + + + diff --git a/AspireApp/AspireApp.ServiceDefaults/Extensions.cs b/AspireApp/AspireApp.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..ef9e0c9d --- /dev/null +++ b/AspireApp/AspireApp.ServiceDefaults/Extensions.cs @@ -0,0 +1,118 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace Microsoft.Extensions.Hosting; + +// Adds common .NET Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// This project should be referenced by each service project in your solution. +// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults +public static class Extensions +{ + 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() + // 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("/health"); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks("/alive", new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..0728cfd2 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №3 "Интеграционное тестирование" + Вариант №26 "Учебный курс" + Выполнена Куспанова Дания 6512 + Ссылка на форк diff --git a/Client.Wasm/Program.cs b/Client.Wasm/Program.cs index a182a920..cf43fc02 100644 --- a/Client.Wasm/Program.cs +++ b/Client.Wasm/Program.cs @@ -9,6 +9,7 @@ builder.RootComponents.Add("#app"); builder.RootComponents.Add("head::after"); +var apiBaseUrl = builder.Configuration["ApiBaseUrl"] ?? "https://localhost:7185/training-course/"; builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); builder.Services.AddBlazorise(options => { options.Immediate = true; }) .AddBootstrapProviders() 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..b97c3ac5 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7185/training-course" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..d91ea49f 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -1,25 +1,61 @@ - -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}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {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 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {90FE6B04-8381-437E-893A-FEBA1DA10AEE} - EndGlobalSection -EndGlobal + +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}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspireApp.AppHost", "AspireApp\AspireApp.AppHost\AspireApp.AppHost.csproj", "{A29837DE-20C1-485D-8A15-20290F913552}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspireApp.ServiceDefaults", "AspireApp\AspireApp.ServiceDefaults\AspireApp.ServiceDefaults.csproj", "{792C7D55-018A-45EC-8437-5A96B7E2B23F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Service.Api", "Service.Api\Service.Api.csproj", "{6AA6D305-55E5-4379-87E5-F0ED5E347B49}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{918C028A-F3FC-4A78-B9F2-199193B8949E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "File.Service", "File.Service\File.Service.csproj", "{DF944664-05C9-E01F-B262-C8B381C1EFE1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspireApp.AppHost.Tests", "AspireApp\AspireApp.AppHost.Tests\AspireApp.AppHost.Tests.csproj", "{C7D17A52-5C07-4A78-ABDF-E00CD8F3C685}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {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 + {A29837DE-20C1-485D-8A15-20290F913552}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A29837DE-20C1-485D-8A15-20290F913552}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A29837DE-20C1-485D-8A15-20290F913552}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A29837DE-20C1-485D-8A15-20290F913552}.Release|Any CPU.Build.0 = Release|Any CPU + {792C7D55-018A-45EC-8437-5A96B7E2B23F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {792C7D55-018A-45EC-8437-5A96B7E2B23F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {792C7D55-018A-45EC-8437-5A96B7E2B23F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {792C7D55-018A-45EC-8437-5A96B7E2B23F}.Release|Any CPU.Build.0 = Release|Any CPU + {6AA6D305-55E5-4379-87E5-F0ED5E347B49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6AA6D305-55E5-4379-87E5-F0ED5E347B49}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6AA6D305-55E5-4379-87E5-F0ED5E347B49}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6AA6D305-55E5-4379-87E5-F0ED5E347B49}.Release|Any CPU.Build.0 = Release|Any CPU + {918C028A-F3FC-4A78-B9F2-199193B8949E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {918C028A-F3FC-4A78-B9F2-199193B8949E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {918C028A-F3FC-4A78-B9F2-199193B8949E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {918C028A-F3FC-4A78-B9F2-199193B8949E}.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 + {C7D17A52-5C07-4A78-ABDF-E00CD8F3C685}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C7D17A52-5C07-4A78-ABDF-E00CD8F3C685}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C7D17A52-5C07-4A78-ABDF-E00CD8F3C685}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C7D17A52-5C07-4A78-ABDF-E00CD8F3C685}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {90FE6B04-8381-437E-893A-FEBA1DA10AEE} + EndGlobalSection +EndGlobal diff --git a/File.Service/Controllers/S3StorageController.cs b/File.Service/Controllers/S3StorageController.cs new file mode 100644 index 00000000..9e86156d --- /dev/null +++ b/File.Service/Controllers/S3StorageController.cs @@ -0,0 +1,61 @@ +using File.Service.Storage; +using Microsoft.AspNetCore.Mvc; +using System.Text; +using System.Text.Json.Nodes; + +namespace File.Service.Controllers; + +/// +/// Контроллер для взаимодействия с объектным хранилищем учебных курсов +/// +/// Служба для работы с объектным хранилищем +/// Логгер +[ApiController] +[Route("api/s3")] +public class S3StorageController(IS3Service s3Service, ILogger logger) : ControllerBase +{ + /// + /// Возвращает список ключей файлов, хранящихся в бакете + /// + [HttpGet] + [ProducesResponseType(200)] + [ProducesResponseType(500)] + public async Task>> ListFiles() + { + logger.LogInformation("Вызван метод {method} контроллера {controller}", nameof(ListFiles), nameof(S3StorageController)); + try + { + var list = await s3Service.GetFileList(); + logger.LogInformation("Получен список из {count} файлов в бакете", list.Count); + return Ok(list); + } + catch (Exception ex) + { + logger.LogError(ex, "Исключение при выполнении {method} в {controller}", nameof(ListFiles), nameof(S3StorageController)); + return BadRequest(ex.Message); + } + } + + /// + /// Возвращает JSON-представление файла, хранящегося в бакете + /// + /// Ключ файла + [HttpGet("{key}")] + [ProducesResponseType(200)] + [ProducesResponseType(500)] + public async Task> GetFile(string key) + { + logger.LogInformation("Вызван метод {method} контроллера {controller}", nameof(GetFile), nameof(S3StorageController)); + try + { + var node = await s3Service.DownloadFile(key); + logger.LogInformation("Получен JSON размером {size} байт", Encoding.UTF8.GetByteCount(node.ToJsonString())); + return Ok(node); + } + catch (Exception ex) + { + logger.LogError(ex, "Исключение при выполнении {method} в {controller}", nameof(GetFile), nameof(S3StorageController)); + return BadRequest(ex.Message); + } + } +} diff --git a/File.Service/Controllers/SnsSubscriberController.cs b/File.Service/Controllers/SnsSubscriberController.cs new file mode 100644 index 00000000..4e732efa --- /dev/null +++ b/File.Service/Controllers/SnsSubscriberController.cs @@ -0,0 +1,86 @@ +using Amazon.SimpleNotificationService.Util; +using File.Service.Storage; +using Microsoft.AspNetCore.Mvc; +using System.Text; + +namespace File.Service.Controllers; + +/// +/// Контроллер для приёма сообщений от SNS-топика +/// +/// Служба для работы с объектным хранилищем +/// Конфигурация приложения +/// Логгер +[ApiController] +[Route("api/sns")] +public class SnsSubscriberController( + IS3Service s3Service, + IConfiguration configuration, + ILogger logger) : ControllerBase +{ + /// + /// Адрес LocalStack, используемый для подтверждения подписки SNS изнутри контейнера + /// + private readonly string _confirmationHost = configuration["AWS:Resources:SubscriptionConfirmationHost"] + ?? throw new KeyNotFoundException("Хост для подтверждения подписки SNS не найден в конфигурации"); + + /// + /// Порт LocalStack, используемый для подтверждения подписки SNS + /// + private readonly int _confirmationPort = int.TryParse( + configuration["AWS:Resources:SubscriptionConfirmationPort"], out var port) + ? port + : throw new KeyNotFoundException("Порт для подтверждения подписки SNS не найден в конфигурации"); + + /// + /// Webhook, принимающий уведомления и подтверждения подписки SNS-топика + /// + /// + /// Эндпоинт используется как для приёма уведомлений, так и для подтверждения подписки + /// при инициализации информационного обмена. В обоих случаях должен возвращать 200. + /// + [HttpPost] + [ProducesResponseType(200)] + public async Task ReceiveMessage() + { + logger.LogInformation("Вызван SNS webhook"); + 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("Получен запрос на подтверждение подписки"); + using var httpClient = new HttpClient(); + var builder = new UriBuilder(new Uri(snsMessage.SubscribeURL)) + { + Scheme = "http", + Host = _confirmationHost, + Port = _confirmationPort + }; + var response = await httpClient.GetAsync(builder.Uri); + if (!response.IsSuccessStatusCode) + { + var body = await response.Content.ReadAsStringAsync(); + throw new Exception($"SubscriptionConfirmation вернул {response.StatusCode}: {body}"); + } + logger.LogInformation("Подписка успешно подтверждена"); + return Ok(); + } + + if (snsMessage.Type == "Notification") + { + await s3Service.UploadFile(snsMessage.MessageText); + logger.LogInformation("Уведомление обработано и сохранено в хранилище"); + } + } + catch (Exception ex) + { + logger.LogError(ex, "Исключение при обработке SNS-уведомления"); + } + return Ok(); + } +} diff --git a/File.Service/File.Service.csproj b/File.Service/File.Service.csproj new file mode 100644 index 00000000..362701ec --- /dev/null +++ b/File.Service/File.Service.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/File.Service/Messaging/SnsSubscriptionService.cs b/File.Service/Messaging/SnsSubscriptionService.cs new file mode 100644 index 00000000..fd5b5479 --- /dev/null +++ b/File.Service/Messaging/SnsSubscriptionService.cs @@ -0,0 +1,42 @@ +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; +using System.Net; + +namespace File.Service.Messaging; + +/// +/// Служба, оформляющая подписку файлового сервиса на SNS-топик при старте приложения +/// +/// Клиент SNS +/// Конфигурация приложения +/// Логгер +public class SnsSubscriptionService( + IAmazonSimpleNotificationService snsClient, + IConfiguration configuration, + ILogger logger) +{ + private readonly string _topicArn = configuration["AWS:Resources:SNSTopicArn"] + ?? throw new KeyNotFoundException("ARN SNS-топика не найден в конфигурации"); + + /// + /// Отправляет запрос на подписку HTTP-эндпоинта файлового сервиса в SNS-топик + /// + public async Task SubscribeEndpoint() + { + logger.LogInformation("Отправка запроса на подписку для топика {topic}", _topicArn); + var endpoint = configuration["AWS:Resources:SNSUrl"]; + + 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("Не удалось подписаться на топик {topic}", _topicArn); + else + logger.LogInformation("Запрос на подписку для {topic} успешно отправлен, ожидается подтверждение", _topicArn); + } +} diff --git a/File.Service/Program.cs b/File.Service/Program.cs new file mode 100644 index 00000000..84f59990 --- /dev/null +++ b/File.Service/Program.cs @@ -0,0 +1,45 @@ +using Amazon.SimpleNotificationService; +using File.Service.Messaging; +using File.Service.Storage; +using LocalStack.Client.Extensions; +using System.Reflection; + +var builder = WebApplication.CreateBuilder(args); +builder.AddServiceDefaults(); + +builder.Services.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.AddScoped(); + +builder.AddMinioClient("course-minio"); +builder.Services.AddScoped(); + +var app = builder.Build(); +app.MapDefaultEndpoints(); + +using var scope = app.Services.CreateScope(); + +var s3 = scope.ServiceProvider.GetRequiredService(); +await s3.EnsureBucketExists(); + +var subscription = scope.ServiceProvider.GetRequiredService(); +await subscription.SubscribeEndpoint(); + +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..110e4c19 --- /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:7965", + "sslPort": 44318 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5274", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7160;http://localhost:5274", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/File.Service/Storage/IS3Service.cs b/File.Service/Storage/IS3Service.cs new file mode 100644 index 00000000..2f6ed2cc --- /dev/null +++ b/File.Service/Storage/IS3Service.cs @@ -0,0 +1,32 @@ +using System.Text.Json.Nodes; + +namespace File.Service.Storage; + +/// +/// Интерфейс службы для манипуляции файлами в объектном хранилище +/// +public interface IS3Service +{ + /// + /// Сериализует и отправляет файл с учебным курсом в хранилище + /// + /// Строковое представление сохраняемого файла (JSON) + /// Признак успешной загрузки + public Task UploadFile(string fileData); + + /// + /// Получает список ключей всех файлов из хранилища + /// + public Task> GetFileList(); + + /// + /// Получает JSON-представление файла из хранилища + /// + /// Ключ файла в бакете + public Task DownloadFile(string filePath); + + /// + /// Создаёт бакет в хранилище, если он ещё не существует + /// + public Task EnsureBucketExists(); +} diff --git a/File.Service/Storage/S3MinioService.cs b/File.Service/Storage/S3MinioService.cs new file mode 100644 index 00000000..85789ee3 --- /dev/null +++ b/File.Service/Storage/S3MinioService.cs @@ -0,0 +1,129 @@ +using Minio; +using Minio.DataModel.Args; +using System.Net; +using System.Text; +using System.Text.Json.Nodes; + +namespace File.Service.Storage; + +/// +/// Служба для манипуляции файлами учебных курсов в Minio +/// +/// Клиент Minio +/// Конфигурация приложения +/// Логгер +public class S3MinioService( + IMinioClient client, + IConfiguration configuration, + ILogger logger) : IS3Service +{ + private readonly string _bucketName = configuration["AWS:Resources:MinioBucketName"] + ?? throw new KeyNotFoundException("Имя бакета Minio не найдено в конфигурации"); + + /// + public async Task> GetFileList() + { + var list = new List(); + var request = new ListObjectsArgs() + .WithBucket(_bucketName) + .WithPrefix("") + .WithRecursive(true); + logger.LogInformation("Запрос списка файлов в {bucket}", _bucketName); + var responseList = client.ListObjectsEnumAsync(request); + + if (responseList == null) + logger.LogWarning("Из {bucket} получен пустой ответ", _bucketName); + + await foreach (var response in responseList!) + list.Add(response.Key); + return list; + } + + /// + public async Task UploadFile(string fileData) + { + var rootNode = JsonNode.Parse(fileData) ?? throw new ArgumentException("Переданная строка не является валидным JSON"); + var id = rootNode["id"]?.GetValue() ?? throw new ArgumentException("JSON имеет некорректную структуру"); + + var bytes = Encoding.UTF8.GetBytes(fileData); + using var stream = new MemoryStream(bytes); + stream.Seek(0, SeekOrigin.Begin); + + logger.LogInformation("Загрузка учебного курса {file} в {bucket}", id, _bucketName); + var request = new PutObjectArgs() + .WithBucket(_bucketName) + .WithStreamData(stream) + .WithObjectSize(bytes.Length) + .WithObject($"training_course_{id}.json"); + + var response = await client.PutObjectAsync(request); + + if (response.ResponseStatusCode != HttpStatusCode.OK) + { + logger.LogError("Не удалось загрузить учебный курс {file}: {code}", id, response.ResponseStatusCode); + return false; + } + logger.LogInformation("Учебный курс {file} успешно загружен в {bucket}", id, _bucketName); + return true; + } + + /// + public async Task DownloadFile(string key) + { + logger.LogInformation("Скачивание {file} из {bucket}", key, _bucketName); + + try + { + var memoryStream = new MemoryStream(); + + var request = new GetObjectArgs() + .WithBucket(_bucketName) + .WithObject(key) + .WithCallbackStream(async (stream, cancellationToken) => + { + await stream.CopyToAsync(memoryStream, cancellationToken); + memoryStream.Seek(0, SeekOrigin.Begin); + }); + + var response = await client.GetObjectAsync(request); + + if (response == null) + { + logger.LogError("Не удалось скачать {file}", key); + throw new InvalidOperationException($"Ошибка при скачивании {key} — объект равен null"); + } + using var reader = new StreamReader(memoryStream, Encoding.UTF8); + return JsonNode.Parse(reader.ReadToEnd()) + ?? throw new InvalidOperationException("Скачанный документ не является валидным JSON"); + } + catch (Exception ex) + { + logger.LogError(ex, "Исключение при скачивании файла {file}", key); + throw; + } + } + + /// + public async Task EnsureBucketExists() + { + logger.LogInformation("Проверка существования бакета {bucket}", _bucketName); + try + { + var existsRequest = new BucketExistsArgs().WithBucket(_bucketName); + var exists = await client.BucketExistsAsync(existsRequest); + if (!exists) + { + logger.LogInformation("Создание бакета {bucket}", _bucketName); + var createRequest = new MakeBucketArgs().WithBucket(_bucketName); + await client.MakeBucketAsync(createRequest); + return; + } + logger.LogInformation("Бакет {bucket} существует", _bucketName); + } + catch (Exception ex) + { + logger.LogError(ex, "Необработанное исключение при проверке бакета {bucket}", _bucketName); + throw; + } + } +} diff --git a/File.Service/appsettings.Development.json b/File.Service/appsettings.Development.json new file mode 100644 index 00000000..ff66ba6b --- /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..03ca1750 --- /dev/null +++ b/File.Service/appsettings.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "AWS": { + "Resources": { + "SubscriptionConfirmationHost": "localhost", + "SubscriptionConfirmationPort": "4566" + } + } +} diff --git a/Service.Api/Entities/TrainingCourse.cs b/Service.Api/Entities/TrainingCourse.cs new file mode 100644 index 00000000..8e179703 --- /dev/null +++ b/Service.Api/Entities/TrainingCourse.cs @@ -0,0 +1,69 @@ +using System.Text.Json.Serialization; + +namespace Service.Api.Entities; + +/// +/// Учебный курс +/// +public class TrainingCourse +{ + /// + /// Идентификатор курса в системе + /// + [JsonPropertyName("id")] + public int Id { get; set; } + + /// + /// Наименование курса + /// + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// + /// ФИО преподавателя (фамилия, имя, отчество через пробел) + /// + [JsonPropertyName("teacherFullName")] + public string TeacherFullName { get; set; } = string.Empty; + + /// + /// Дата начала курса + /// + [JsonPropertyName("startDate")] + public DateOnly StartDate { get; set; } + + /// + /// Дата окончания курса + /// + [JsonPropertyName("endDate")] + public DateOnly EndDate { get; set; } + + /// + /// Максимальное число студентов + /// + [JsonPropertyName("maxStudents")] + public int MaxStudents { get; set; } + + /// + /// Текущее число студентов + /// + [JsonPropertyName("currentStudents")] + public int CurrentStudents { get; set; } + + /// + /// Выдача сертификата по окончании + /// + [JsonPropertyName("hasCertificate")] + public bool HasCertificate { get; set; } + + /// + /// Стоимость курса + /// + [JsonPropertyName("price")] + public decimal Price { get; set; } + + /// + /// Рейтинг курса (от 1 до 5) + /// + [JsonPropertyName("rating")] + public int Rating { get; set; } +} \ No newline at end of file diff --git a/Service.Api/Generator/GeneratorService.cs b/Service.Api/Generator/GeneratorService.cs new file mode 100644 index 00000000..5be181e3 --- /dev/null +++ b/Service.Api/Generator/GeneratorService.cs @@ -0,0 +1,80 @@ +using Microsoft.Extensions.Caching.Distributed; +using Service.Api.Entities; +using Service.Api.Messaging; +using System.Text.Json; + +namespace Service.Api.Generator; + +/// +/// Сервис для генерации и кэширования учебных курсов с публикацией в брокер +/// +/// Распределённый кэш +/// Служба отправки сообщений в брокер +/// Конфигурация приложения +/// Логгер +public class GeneratorService( + IDistributedCache cache, + IProducerService producer, + IConfiguration configuration, + ILogger logger) : IGeneratorService +{ + private readonly TimeSpan _cacheExpiration = int.TryParse(configuration["CacheExpiration"], out var sec) + ? TimeSpan.FromSeconds(sec) + : TimeSpan.FromSeconds(3600); + + /// + /// Возвращает курс из кэша или генерирует новый, публикует его в брокер и кладёт в кэш + /// + public async Task ProcessTrainingCourse(int id) + { + try + { + logger.LogInformation("Начало обработки учебного курса {id}", id); + var trainingCourse = await GetCourseFromCacheAsync(id); + if (trainingCourse != null) + { + return trainingCourse; + } + trainingCourse = TrainingCourseGenerator.GenerateOne(id); + logger.LogInformation("Курс успешно сгенерирован. ID: {CourseId}", trainingCourse.Id); + await producer.SendMessage(trainingCourse); + await SaveCourseToCacheAsync(trainingCourse); + return trainingCourse; + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при обработке курса {CourseId}", id); + return null; + } + } + + /// + /// Получает курс по идентификатору из кэша + /// + private async Task GetCourseFromCacheAsync(int id) + { + var cachedData = await cache.GetStringAsync(id.ToString()); + if (string.IsNullOrEmpty(cachedData)) + { + logger.LogWarning("Курс с ID {CourseId} не найден в кэше", id); + return null; + } + var course = JsonSerializer.Deserialize(cachedData); + logger.LogInformation("Курс с ID {CourseId} был найден в кэше", id); + return course; + } + + /// + /// Сохраняет курс в кэш + /// + private async Task SaveCourseToCacheAsync(TrainingCourse course) + { + logger.LogInformation("Курс с ID {CourseId} добавлен в кэш", course.Id); + var jsonData = JsonSerializer.Serialize(course); + await cache.SetStringAsync(course.Id.ToString(), jsonData, + new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheExpiration + }); + } +} diff --git a/Service.Api/Generator/IGeneratorService.cs b/Service.Api/Generator/IGeneratorService.cs new file mode 100644 index 00000000..3a380872 --- /dev/null +++ b/Service.Api/Generator/IGeneratorService.cs @@ -0,0 +1,15 @@ +using Service.Api.Entities; + +namespace Service.Api.Generator; + +/// +/// Интерфейс для запуска юзкейса по обработке учебного курса +/// +public interface IGeneratorService +{ + /// + /// Генерирует один случайный учебный курс + /// + /// Сгенерированный курс + Task ProcessTrainingCourse(int id); +} diff --git a/Service.Api/Generator/TrainingCourseGenerator.cs b/Service.Api/Generator/TrainingCourseGenerator.cs new file mode 100644 index 00000000..0e885769 --- /dev/null +++ b/Service.Api/Generator/TrainingCourseGenerator.cs @@ -0,0 +1,90 @@ +using Bogus; +using Bogus.DataSets; +using Service.Api.Entities; + +namespace Service.Api.Generator; + +/// +/// Генератор тестовых данных для учебных курсов +/// +public static class TrainingCourseGenerator +{ + private static readonly Faker _courseFaker; + + /// + /// Инициализирует генератор + /// + static TrainingCourseGenerator() + { + var courseNames = new[] + { + "ASP.NET Core разработка", + "Blazor WebAssembly", + "Entity Framework Core", + "React для начинающих", + "Angular продвинутый", + "Python для анализа данных", + "Java Spring Boot", + "Go для микросервисов", + "Docker и Kubernetes", + "SQL оптимизация запросов", + "TypeScript с нуля", + "Vue.js практикум", + "C# алгоритмы", + "Azure DevOps", + "Git и CI/CD" + }; + _courseFaker = new Faker("ru") + .RuleFor(c => c.Id, f => f.IndexFaker + 1) + .RuleFor(c => c.Name, f => f.PickRandom(courseNames)) + .RuleFor(c => c.TeacherFullName, f => + { + var gender = f.PickRandom(); + + var firstName = f.Name.FirstName(gender); + var lastName = f.Name.LastName(gender); + + var patronymicSuffix = gender == Name.Gender.Male ? "ович" : "овна"; + var patronymic = f.Name.FirstName(Name.Gender.Male) + patronymicSuffix; + + return $"{lastName} {firstName} {patronymic}"; + }) + .RuleFor(c => c.StartDate, f => + { + var daysToStart = f.Random.Int(3, 60); + return f.Date.SoonDateOnly(daysToStart); + }) + .RuleFor(c => c.EndDate, (f, c) => + { + var durationDays = f.Random.Int(10, 90); + return c.StartDate.AddDays(durationDays); + }) + .RuleFor(c => c.MaxStudents, f => f.Random.Int(5, 30)) + .RuleFor(c => c.CurrentStudents, (f, c) => + { + var today = DateOnly.FromDateTime(DateTime.Now); + if (c.StartDate <= today) + { + return f.Random.Int(0, c.MaxStudents); + } + return f.Random.Int(0, c.MaxStudents / 2); + }) + .RuleFor(c => c.HasCertificate, f => f.Random.Bool(0.9f)) + .RuleFor(c => c.Price, f => + { + var price = f.Random.Decimal(5000, 150000); + return Math.Round(price, 2); + }) + .RuleFor(c => c.Rating, f => f.Random.Int(1, 5)); + } + + /// + /// Генерирует один учебный курс с конкретным id + /// + public static TrainingCourse GenerateOne(int id) + { + var course = _courseFaker.Generate(); + course.Id = id; + return course; + } +} \ No newline at end of file diff --git a/Service.Api/Messaging/IProducerService.cs b/Service.Api/Messaging/IProducerService.cs new file mode 100644 index 00000000..1b66e5b3 --- /dev/null +++ b/Service.Api/Messaging/IProducerService.cs @@ -0,0 +1,15 @@ +using Service.Api.Entities; + +namespace Service.Api.Messaging; + +/// +/// Интерфейс службы для отправки сгенерированных учебных курсов в брокер сообщений +/// +public interface IProducerService +{ + /// + /// Отправляет сообщение об учебном курсе в брокер + /// + /// Учебный курс + public Task SendMessage(TrainingCourse trainingCourse); +} diff --git a/Service.Api/Messaging/SnsPublisherService.cs b/Service.Api/Messaging/SnsPublisherService.cs new file mode 100644 index 00000000..4bd14e60 --- /dev/null +++ b/Service.Api/Messaging/SnsPublisherService.cs @@ -0,0 +1,45 @@ +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; +using Service.Api.Entities; +using System.Net; +using System.Text.Json; + +namespace Service.Api.Messaging; + +/// +/// Служба для публикации сообщений об учебных курсах в SNS-топик +/// +/// Клиент SNS +/// Конфигурация приложения +/// Логгер +public class SnsPublisherService( + IAmazonSimpleNotificationService client, + IConfiguration configuration, + ILogger logger) : IProducerService +{ + private readonly string _topicArn = configuration["AWS:Resources:SNSTopicArn"] + ?? throw new KeyNotFoundException("SNS topic ARN was not found in configuration"); + + /// + public async Task SendMessage(TrainingCourse trainingCourse) + { + try + { + var json = JsonSerializer.Serialize(trainingCourse); + var request = new PublishRequest + { + Message = json, + TopicArn = _topicArn + }; + var response = await client.PublishAsync(request); + if (response.HttpStatusCode == HttpStatusCode.OK) + logger.LogInformation("Учебный курс {id} был отправлен в SNS-топик", trainingCourse.Id); + else + throw new Exception($"SNS вернул {response.HttpStatusCode}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Не удалось отправить учебный курс {id} в SNS-топик", trainingCourse.Id); + } + } +} diff --git a/Service.Api/Program.cs b/Service.Api/Program.cs new file mode 100644 index 00000000..89a076ac --- /dev/null +++ b/Service.Api/Program.cs @@ -0,0 +1,19 @@ +using Amazon.SimpleNotificationService; +using LocalStack.Client.Extensions; +using Service.Api.Generator; +using Service.Api.Messaging; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("RedisCache"); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +var app = builder.Build(); +app.MapDefaultEndpoints(); +app.MapGet("/training-course", (IGeneratorService service, int id) => service.ProcessTrainingCourse(id)); +app.Run(); diff --git a/Service.Api/Properties/launchSettings.json b/Service.Api/Properties/launchSettings.json new file mode 100644 index 00000000..9e10b559 --- /dev/null +++ b/Service.Api/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:21995", + "sslPort": 44360 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5241", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7077;http://localhost:5241", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Service.Api/Service.Api.csproj b/Service.Api/Service.Api.csproj new file mode 100644 index 00000000..e94079fd --- /dev/null +++ b/Service.Api/Service.Api.csproj @@ -0,0 +1,21 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + diff --git a/Service.Api/appsettings.Development.json b/Service.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Service.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Service.Api/appsettings.json b/Service.Api/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/Service.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +}