diff --git a/Api.Gateway/Api.Gateway.csproj b/Api.Gateway/Api.Gateway.csproj new file mode 100644 index 00000000..28166b99 --- /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..60e9286e --- /dev/null +++ b/Api.Gateway/LoadBalancer/WeightedRandom.cs @@ -0,0 +1,36 @@ +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 frequencies = configuration.GetSection("LoadBalancer:WeightedRandom:Weights").Get(); + if (frequencies == null || frequencies.Length == 0) + throw new InvalidOperationException("LoadBalancer:WeightedRandom:Weights is empty or null. Add weights to configuration"); + _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..adc75f42 --- /dev/null +++ b/Api.Gateway/Program.cs @@ -0,0 +1,26 @@ +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((sp, _, discoveryProvider) => + { + var configuration = sp.GetRequiredService(); + return new WeightedRandom(discoveryProvider.GetAsync, configuration); + }); +builder.Services.AddCors(options => options.AddDefaultPolicy(policy => +{ + policy.WithOrigins("http://localhost:5127") + .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..3043431a --- /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:25431", + "sslPort": 44359 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5190", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7034;http://localhost:5190", + "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..316d9207 --- /dev/null +++ b/Api.Gateway/ocelot.json @@ -0,0 +1,35 @@ +{ + "Routes": [ + { + "UpstreamPathTemplate": "/program-project", + "UpstreamHttpMethod": [ "GET" ], + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 4440 + }, + { + "Host": "localhost", + "Port": 4441 + }, + { + "Host": "localhost", + "Port": 4442 + }, + { + "Host": "localhost", + "Port": 4443 + }, + { + "Host": "localhost", + "Port": 4444 + } + ], + "DownstreamPathTemplate": "/program-project", + "DownstreamScheme": "https", + "LoadBalancerOptions": { + "Type": "WeightedRandom" + } + } + ] +} \ No newline at end of file diff --git a/AspireApp1/AspireApp1.AppHost.Tests/AspireApp.AppHost.Tests.csproj b/AspireApp1/AspireApp1.AppHost.Tests/AspireApp.AppHost.Tests.csproj new file mode 100644 index 00000000..c1a691b9 --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost.Tests/AspireApp.AppHost.Tests.csproj @@ -0,0 +1,33 @@ + + + + net8.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AspireApp1/AspireApp1.AppHost.Tests/IntegrationTest.cs b/AspireApp1/AspireApp1.AppHost.Tests/IntegrationTest.cs new file mode 100644 index 00000000..898b8aa2 --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost.Tests/IntegrationTest.cs @@ -0,0 +1,118 @@ +using Aspire.Hosting; +using Microsoft.Extensions.Logging; +using ServiceApi.Entities; +using System.Text.Json; +using Xunit.Abstractions; + +namespace AspireApp.AppHost.Tests; + +/// +/// Интеграционные тесты для проверки микросервисного пайплайна +/// +/// Служба журналирования юнит-тестов +public class IntegrationTest(ITestOutputHelper output) : IAsyncLifetime +{ + private DistributedApplication? _app; + private HttpClient? _gatewayClient; + private HttpClient? _fileClient; + + /// + 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); + _gatewayClient = _app.CreateHttpClient("api-gateway", "http"); + _fileClient = _app.CreateHttpClient("fileservice", "http"); + } + + /// + /// Проверяет, что вызов гейтвея: + /// + /// В ответ отправляет сгенерированный программный проект + /// Сериализует программный проект в S3 хранилище + /// Данные в ответе гейтвея и в S3 идентичны + /// + /// + [Fact] + public async Task GatewayCall_StoresProgramProjectInS3() + { + var id = Random.Shared.Next(1, 1000); + using var gatewayResponse = await _gatewayClient!.GetAsync($"/program-project?id={id}"); + var apiProject = JsonSerializer.Deserialize(await gatewayResponse.Content.ReadAsStringAsync()); + + await Task.Delay(5000); + using var listResponse = await _fileClient!.GetAsync("/api/s3"); + var fileList = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync()); + using var s3Response = await _fileClient!.GetAsync($"/api/s3/programproject_{id}.json"); + var s3Project = JsonSerializer.Deserialize(await s3Response.Content.ReadAsStringAsync()); + + Assert.NotNull(fileList); + Assert.Single(fileList); + Assert.NotNull(apiProject); + Assert.NotNull(s3Project); + Assert.Equal(id, s3Project.Id); + Assert.Equivalent(apiProject, s3Project); + } + + /// + /// Проверяет, что после генерации двух разных программных проектов + /// в S3 хранилище появляются два разных файла + /// + [Fact] + public async Task TwoDifferentIds_ProduceTwoFilesInS3() + { + var firstId = Random.Shared.Next(1, 500); + var secondId = Random.Shared.Next(501, 1000); + + await _gatewayClient!.GetAsync($"/program-project?id={firstId}"); + await _gatewayClient!.GetAsync($"/program-project?id={secondId}"); + + await Task.Delay(5000); + using var listResponse = await _fileClient!.GetAsync("/api/s3"); + var fileList = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync()); + + Assert.NotNull(fileList); + Assert.Equal(2, fileList.Count); + Assert.Contains($"programproject_{firstId}.json", fileList); + Assert.Contains($"programproject_{secondId}.json", fileList); + } + + /// + /// Проверяет, что повторный запрос того же программного проекта + /// обслуживается из кэша и не приводит к дублирующей отправке в S3 + /// + [Fact] + public async Task RepeatedRequest_DoesNotDuplicateFileInS3() + { + var id = Random.Shared.Next(1, 1000); + + await _gatewayClient!.GetAsync($"/program-project?id={id}"); + await _gatewayClient!.GetAsync($"/program-project?id={id}"); + await _gatewayClient!.GetAsync($"/program-project?id={id}"); + + await Task.Delay(5000); + using var listResponse = await _fileClient!.GetAsync("/api/s3"); + var fileList = JsonSerializer.Deserialize>(await listResponse.Content.ReadAsStringAsync()); + + Assert.NotNull(fileList); + Assert.Single(fileList); + Assert.Equal($"programproject_{id}.json", fileList[0]); + } + + /// + public async Task DisposeAsync() + { + await _app!.StopAsync(); + await _app.DisposeAsync(); + } +} diff --git a/AspireApp1/AspireApp1.AppHost/AspireApp.AppHost.csproj b/AspireApp1/AspireApp1.AppHost/AspireApp.AppHost.csproj new file mode 100644 index 00000000..3702fde0 --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost/AspireApp.AppHost.csproj @@ -0,0 +1,33 @@ + + + + + + Exe + net8.0 + enable + enable + true + af866732-ee76-4a9f-b28a-2e8d52f5e153 + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/AspireApp1/AspireApp1.AppHost/CloudFormation/programproject-template-sqs-s3.yaml b/AspireApp1/AspireApp1.AppHost/CloudFormation/programproject-template-sqs-s3.yaml new file mode 100644 index 00000000..44d390f3 --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost/CloudFormation/programproject-template-sqs-s3.yaml @@ -0,0 +1,62 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: 'Cloud formation template for program project' + +Parameters: + BucketName: + Type: String + Description: Name for the S3 bucket + Default: 'programproject-bucket' + + QueueName: + Type: String + Description: Name for the SQS queue + Default: 'programproject-queue' + +Resources: + ProgramProjectBucket: + 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 + + ProgramProjectQueue: + Type: AWS::SQS::Queue + Properties: + QueueName: !Ref QueueName + VisibilityTimeout: 30 + MessageRetentionPeriod: 345600 + DelaySeconds: 0 + ReceiveMessageWaitTimeSeconds: 0 + Tags: + - Key: Name + Value: !Ref QueueName + - Key: Environment + Value: Sample + +Outputs: + S3BucketName: + Description: Name of the S3 bucket + Value: !Ref ProgramProjectBucket + + S3BucketArn: + Description: ARN of the S3 bucket + Value: !GetAtt ProgramProjectBucket.Arn + + SQSQueueName: + Description: Name of the SQS queue + Value: !GetAtt ProgramProjectQueue.QueueName + + SQSQueueArn: + Description: ARN of the SQS queue + Value: !GetAtt ProgramProjectQueue.Arn diff --git a/AspireApp1/AspireApp1.AppHost/CloudFormation/sqs-s3.yaml b/AspireApp1/AspireApp1.AppHost/CloudFormation/sqs-s3.yaml new file mode 100644 index 00000000..541d26b4 --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost/CloudFormation/sqs-s3.yaml @@ -0,0 +1,35 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: 'Cloud formation for program project with SQS and S3' + +Parameters: + BucketName: + Type: String + Default: 'project-bucket' + + QueueName: + Type: String + Default: 'project-queue' + +Resources: + ProjectBucket: + Type: AWS::S3::Bucket + Properties: + BucketName: !Ref BucketName + + ProjectQueue: + Type: AWS::SQS::Queue + Properties: + QueueName: !Ref QueueName + +Outputs: + S3BucketName: + Value: !Ref ProjectBucket + + S3BucketArn: + Value: !GetAtt ProjectBucket.Arn + + SQSQueueName: + Value: !GetAtt ProjectQueue.QueueName + + SQSQueueArn: + Value: !GetAtt ProjectQueue.Arn \ No newline at end of file diff --git a/AspireApp1/AspireApp1.AppHost/Program.cs b/AspireApp1/AspireApp1.AppHost/Program.cs new file mode 100644 index 00000000..0e6b48e6 --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost/Program.cs @@ -0,0 +1,49 @@ +using Amazon; +using Aspire.Hosting.LocalStack.Container; + +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("project-cache") + .WithRedisInsight(containerName: "project-insight"); + +var gateway = builder.AddProject("api-gateway"); + +var awsConfig = builder.AddAWSSDKConfig() + .WithProfile("default") + .WithRegion(RegionEndpoint.EUCentral1); + +var localstack = builder + .AddLocalStack("project-localstack", awsConfig: awsConfig, configureContainer: container => + { + container.Lifetime = ContainerLifetime.Session; + container.DebugLevel = 1; + container.LogLevel = LocalStackLogLevel.Debug; + container.Port = 4566; + container.AdditionalEnvironmentVariables.Add("DEBUG", "1"); + }); + +var awsResources = builder + .AddAWSCloudFormationTemplate("resources", "CloudFormation/programproject-template-sqs-s3.yaml", "programproject") + .WithReference(awsConfig); + +for (var i = 0; i < 5; i++) +{ + var service = builder.AddProject($"programproject-api-{i + 1}", launchProfileName: null) + .WithHttpsEndpoint(4440 + i) + .WithReference(cache, "RedisCache") + .WithReference(awsResources) + .WaitFor(cache) + .WaitFor(awsResources); + gateway.WaitFor(service); +} + +builder.AddProject("programproject-wasm") + .WaitFor(gateway); + +builder.AddProject("fileservice") + .WithReference(awsResources) + .WaitFor(awsResources); + +builder.UseLocalStack(localstack); + +builder.Build().Run(); diff --git a/AspireApp1/AspireApp1.AppHost/Properties/launchSettings.json b/AspireApp1/AspireApp1.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..600cd4a8 --- /dev/null +++ b/AspireApp1/AspireApp1.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:17188;http://localhost:15202", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21110", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22049" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15202", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19166", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20080" + } + } + } +} diff --git a/AspireApp1/AspireApp1.AppHost/appsettings.Development.json b/AspireApp1/AspireApp1.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/AspireApp1/AspireApp1.AppHost/appsettings.json b/AspireApp1/AspireApp1.AppHost/appsettings.json new file mode 100644 index 00000000..50e14ab7 --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "Localstack": { + "UseLocalstack": true + } +} diff --git a/AspireApp1/AspireApp1.ServiceDefaults/AspireApp.ServiceDefaults.csproj b/AspireApp1/AspireApp1.ServiceDefaults/AspireApp.ServiceDefaults.csproj new file mode 100644 index 00000000..6c036a13 --- /dev/null +++ b/AspireApp1/AspireApp1.ServiceDefaults/AspireApp.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/AspireApp1/AspireApp1.ServiceDefaults/Extensions.cs b/AspireApp1/AspireApp1.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..13151bf4 --- /dev/null +++ b/AspireApp1/AspireApp1.ServiceDefaults/Extensions.cs @@ -0,0 +1,119 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.ServiceDiscovery; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace Microsoft.Extensions.Hosting; + +// Adds common .NET Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// This project should be referenced by each service project in your solution. +// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults +public static class Extensions +{ + 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..c2f8362c 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №3 "Интеграционное тестирование" + Вариант №33 "Программный проект" + Выполнена Солдатовой Ксенией 6512 + Ссылка на форк diff --git a/Client.Wasm/Program.cs b/Client.Wasm/Program.cs index a182a920..c8b49a5a 100644 --- a/Client.Wasm/Program.cs +++ b/Client.Wasm/Program.cs @@ -10,6 +10,7 @@ builder.RootComponents.Add("head::after"); builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); + builder.Services.AddBlazorise(options => { options.Immediate = true; }) .AddBootstrapProviders() .AddFontAwesomeIcons(); diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea7..547fa5e2 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -19,16 +19,6 @@ "ASPNETCORE_ENVIRONMENT": "Development" } }, - "https": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", - "applicationUrl": "https://localhost:7282;http://localhost:5127", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..ad7d8ab4 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -5,6 +5,5 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7034/program-project" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..3beacf45 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,6 +5,18 @@ VisualStudioVersion = 17.14.36811.4 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspireApp.AppHost", "AspireApp1\AspireApp1.AppHost\AspireApp.AppHost.csproj", "{62336D73-9D19-4083-8710-E36C84C094E7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspireApp.ServiceDefaults", "AspireApp1\AspireApp1.ServiceDefaults\AspireApp.ServiceDefaults.csproj", "{5685597E-AE0E-43C5-B825-CB2E000875B3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServiceApi", "ServiceApi\ServiceApi.csproj", "{AB495A22-AE1C-4648-9B97-A4A41C27DA5F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{F2480B81-02E5-44AD-8E32-6611DDC94471}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileService", "FileService\FileService.csproj", "{A253CE7F-B8F0-05C1-ADB0-29BB6768D575}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspireApp.AppHost.Tests", "AspireApp1\AspireApp1.AppHost.Tests\AspireApp.AppHost.Tests.csproj", "{937DCC3A-4864-4272-9249-353A49D6437A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +27,30 @@ Global {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU + {62336D73-9D19-4083-8710-E36C84C094E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {62336D73-9D19-4083-8710-E36C84C094E7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {62336D73-9D19-4083-8710-E36C84C094E7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {62336D73-9D19-4083-8710-E36C84C094E7}.Release|Any CPU.Build.0 = Release|Any CPU + {5685597E-AE0E-43C5-B825-CB2E000875B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5685597E-AE0E-43C5-B825-CB2E000875B3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5685597E-AE0E-43C5-B825-CB2E000875B3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5685597E-AE0E-43C5-B825-CB2E000875B3}.Release|Any CPU.Build.0 = Release|Any CPU + {AB495A22-AE1C-4648-9B97-A4A41C27DA5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB495A22-AE1C-4648-9B97-A4A41C27DA5F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB495A22-AE1C-4648-9B97-A4A41C27DA5F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB495A22-AE1C-4648-9B97-A4A41C27DA5F}.Release|Any CPU.Build.0 = Release|Any CPU + {F2480B81-02E5-44AD-8E32-6611DDC94471}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F2480B81-02E5-44AD-8E32-6611DDC94471}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F2480B81-02E5-44AD-8E32-6611DDC94471}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F2480B81-02E5-44AD-8E32-6611DDC94471}.Release|Any CPU.Build.0 = Release|Any CPU + {A253CE7F-B8F0-05C1-ADB0-29BB6768D575}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A253CE7F-B8F0-05C1-ADB0-29BB6768D575}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A253CE7F-B8F0-05C1-ADB0-29BB6768D575}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A253CE7F-B8F0-05C1-ADB0-29BB6768D575}.Release|Any CPU.Build.0 = Release|Any CPU + {937DCC3A-4864-4272-9249-353A49D6437A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {937DCC3A-4864-4272-9249-353A49D6437A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {937DCC3A-4864-4272-9249-353A49D6437A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {937DCC3A-4864-4272-9249-353A49D6437A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/FileService/Controllers/S3StorageController.cs b/FileService/Controllers/S3StorageController.cs new file mode 100644 index 00000000..482a913e --- /dev/null +++ b/FileService/Controllers/S3StorageController.cs @@ -0,0 +1,57 @@ +using FileService.Storage; +using Microsoft.AspNetCore.Mvc; +using System.Text.Json.Nodes; + +namespace FileService.Controllers; + +/// +/// Контроллер для взаимодействия с S3 +/// +/// Служба для работы с S3 +/// Логгер +[ApiController] +[Route("api/s3")] +public class S3StorageController(IS3Service s3Service, ILogger logger) : ControllerBase +{ + /// + /// Получение списка хранящихся в S3 файлов + /// + [HttpGet] + [ProducesResponseType(200)] + [ProducesResponseType(400)] + public async Task>> ListFiles() + { + try + { + var list = await s3Service.GetFileList(); + logger.LogInformation("Получен список из {count} файлов", list.Count); + return Ok(list); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при получении списка файлов"); + return BadRequest(ex.Message); + } + } + + /// + /// Получение содержимого хранящегося в S3 документа + /// + /// Ключ файла + [HttpGet("{key}")] + [ProducesResponseType(200)] + [ProducesResponseType(400)] + public async Task> GetFile(string key) + { + try + { + var node = await s3Service.DownloadFile(key); + return Ok(node); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при скачивании файла {key}", key); + return BadRequest(ex.Message); + } + } +} diff --git a/FileService/FileService.csproj b/FileService/FileService.csproj new file mode 100644 index 00000000..4bc4a57a --- /dev/null +++ b/FileService/FileService.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + true + $(NoWarn);1591 + + + + + + + + + + + + + + + diff --git a/FileService/Messaging/SqsConsumerService.cs b/FileService/Messaging/SqsConsumerService.cs new file mode 100644 index 00000000..24d5b37f --- /dev/null +++ b/FileService/Messaging/SqsConsumerService.cs @@ -0,0 +1,62 @@ +using Amazon.SQS; +using Amazon.SQS.Model; +using FileService.Storage; + +namespace FileService.Messaging; + +/// +/// Клиентская служба для приема сообщений из очереди SQS и сохранения их в S3 +/// +/// Клиент SQS +/// Фабрика контекста +/// Конфигурация +/// Логгер +public class SqsConsumerService( + IAmazonSQS sqsClient, + IServiceScopeFactory scopeFactory, + IConfiguration configuration, + ILogger logger) : BackgroundService +{ + private readonly string _queueName = configuration["AWS:Resources:SQSQueueName"] + ?? throw new KeyNotFoundException("SQS queue name was not found in configuration"); + + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + logger.LogInformation("Служба SQS-консьюмера запущена."); + + while (!stoppingToken.IsCancellationRequested) + { + var response = await sqsClient.ReceiveMessageAsync( + new ReceiveMessageRequest + { + QueueUrl = _queueName, + MaxNumberOfMessages = 10, + WaitTimeSeconds = 5 + }, stoppingToken); + + if (response.Messages is null) + continue; + + logger.LogInformation("Получено {count} сообщений", response.Messages.Count); + + foreach (var message in response.Messages) + { + try + { + logger.LogInformation("Обработка сообщения: {messageId}", message.MessageId); + + using var scope = scopeFactory.CreateScope(); + var s3Service = scope.ServiceProvider.GetRequiredService(); + await s3Service.UploadFile(message.Body); + + await sqsClient.DeleteMessageAsync(_queueName, message.ReceiptHandle, stoppingToken); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка обработки сообщения: {messageId}", message.MessageId); + } + } + } + } +} diff --git a/FileService/Program.cs b/FileService/Program.cs new file mode 100644 index 00000000..e1557d3e --- /dev/null +++ b/FileService/Program.cs @@ -0,0 +1,41 @@ +using Amazon.S3; +using Amazon.SQS; +using FileService.Messaging; +using FileService.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 (File.Exists(xmlPath)) + options.IncludeXmlComments(xmlPath); +}); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddAwsService(); +builder.Services.AddScoped(); +builder.Services.AddHostedService(); + +var app = builder.Build(); + +using var scope = app.Services.CreateScope(); +var s3Service = scope.ServiceProvider.GetRequiredService(); +await s3Service.EnsureBucketExists(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapDefaultEndpoints(); +app.MapControllers(); +app.Run(); diff --git a/FileService/Properties/launchSettings.json b/FileService/Properties/launchSettings.json new file mode 100644 index 00000000..3ea85afc --- /dev/null +++ b/FileService/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:30765", + "sslPort": 44395 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5053", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7180;http://localhost:5053", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/FileService/Storage/IS3Service.cs b/FileService/Storage/IS3Service.cs new file mode 100644 index 00000000..157c31fc --- /dev/null +++ b/FileService/Storage/IS3Service.cs @@ -0,0 +1,31 @@ +using System.Text.Json.Nodes; + +namespace FileService.Storage; + +/// +/// Интерфейс службы для работы с файлами в объектном хранилище +/// +public interface IS3Service +{ + /// + /// Отправляет файл в хранилище + /// + /// Строковая репрезентация сохраняемого файла + public Task UploadFile(string fileData); + + /// + /// Получает список всех файлов из хранилища + /// + public Task> GetFileList(); + + /// + /// Получает строковую репрезентацию файла из хранилища + /// + /// Ключ файла в бакете + public Task DownloadFile(string key); + + /// + /// Создает бакет, если его еще нет + /// + public Task EnsureBucketExists(); +} diff --git a/FileService/Storage/S3AwsService.cs b/FileService/Storage/S3AwsService.cs new file mode 100644 index 00000000..f13dc106 --- /dev/null +++ b/FileService/Storage/S3AwsService.cs @@ -0,0 +1,97 @@ +using Amazon.S3; +using Amazon.S3.Model; +using System.Net; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace FileService.Storage; + +/// +/// Служба для работы с файлами в объектном хранилище S3 (LocalStack) +/// +/// S3 клиент +/// Конфигурация +/// Логер +public class S3AwsService(IAmazonS3 client, IConfiguration configuration, ILogger logger) : IS3Service +{ + 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("Получение списка файлов из {bucket}", _bucketName); + await foreach (var response in paginator.Responses) + if (response?.S3Objects != null) + foreach (var obj in response.S3Objects) + if (obj != null) + list.Add(obj.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 имеет неверную структуру"); + + using var stream = new MemoryStream(); + JsonSerializer.Serialize(stream, rootNode); + stream.Seek(0, SeekOrigin.Begin); + + logger.LogInformation("Загрузка программного проекта {file} в {bucket}", id, _bucketName); + var request = new PutObjectRequest + { + BucketName = _bucketName, + Key = $"programproject_{id}.json", + InputStream = stream + }; + + var response = await client.PutObjectAsync(request); + + if (response.HttpStatusCode != HttpStatusCode.OK) + { + logger.LogError("Не удалось загрузить программный проект {file}: {code}", id, response.HttpStatusCode); + return false; + } + logger.LogInformation("Программный проект {file} загружен в {bucket}", id, _bucketName); + return true; + } + + /// + public async Task DownloadFile(string key) + { + logger.LogInformation("Скачивание {file} из {bucket}", key, _bucketName); + var request = new GetObjectRequest + { + BucketName = _bucketName, + Key = key + }; + using var response = await client.GetObjectAsync(request); + + if (response.HttpStatusCode != HttpStatusCode.OK) + throw new InvalidOperationException($"Ошибка при скачивании {key} - {response.HttpStatusCode}"); + + using var reader = new StreamReader(response.ResponseStream, Encoding.UTF8); + return JsonNode.Parse(await reader.ReadToEndAsync()) + ?? throw new InvalidOperationException("Скачанный документ не является валидным JSON"); + } + + /// + public async Task EnsureBucketExists() + { + logger.LogInformation("Проверка существования {bucket}", _bucketName); + await client.EnsureBucketExistsAsync(_bucketName); + logger.LogInformation("Существование {bucket} подтверждено", _bucketName); + } +} diff --git a/FileService/appsettings.Development.json b/FileService/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/FileService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/FileService/appsettings.json b/FileService/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/FileService/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/ServiceApi/Entities/ProgramProject.cs b/ServiceApi/Entities/ProgramProject.cs new file mode 100644 index 00000000..56e9435e --- /dev/null +++ b/ServiceApi/Entities/ProgramProject.cs @@ -0,0 +1,66 @@ +using System.Text.Json.Serialization; + +namespace ServiceApi.Entities; + +public class ProgramProject +{ + /// + /// Идентификатор + /// + [JsonPropertyName("id")] + public required int Id { get; set; } + + /// + /// Название проекта + /// + [JsonPropertyName("name")] + public required string Name { get; set; } + + /// + /// Заказчик проекта + /// + [JsonPropertyName("customer")] + public required string Customer { get; set; } + + /// + /// Менеджер проекта + /// + [JsonPropertyName("manager")] + public required string Manager { get; set; } + + /// + /// Дата начала + /// + [JsonPropertyName("startDate")] + public required DateOnly StartDate { get; set; } + + /// + /// Плановая дата завершения + /// + [JsonPropertyName("planEndDate")] + public required DateOnly PlanEndDate { get; set; } + + /// + /// Фактическая дата завершения + /// + [JsonPropertyName("actualEndDate")] + public DateOnly? ActualEndDate { get; set; } + + /// + /// Бюджет + /// + [JsonPropertyName("budget")] + public required decimal Budget { get; set; } + + /// + /// Фактические затраты + /// + [JsonPropertyName("actualCost")] + public required decimal ActualCost { get; set; } + + /// + /// Процент выполнения + /// + [JsonPropertyName("percentComplete")] + public required int PercentComplete { get; set; } +} \ No newline at end of file diff --git a/ServiceApi/Generator/GeneratorService.cs b/ServiceApi/Generator/GeneratorService.cs new file mode 100644 index 00000000..7449ecbd --- /dev/null +++ b/ServiceApi/Generator/GeneratorService.cs @@ -0,0 +1,39 @@ +using ServiceApi.Entities; +using ServiceApi.Messaging; + +namespace ServiceApi.Generator; + +/// +/// Служба для запуска usecase по обработке программных проектов +/// +/// Кэш +/// Служба для взаимодействия с брокером +/// Логгер +public class GeneratorService(IProgramProjectCache cache, IProducerService producer, ILogger logger) : IGeneratorService +{ + public async Task ProcessProgramProject(int id) + { + logger.LogInformation("Начало обработки программного проекта {id}", id); + try + { + logger.LogInformation("Попытка получить {id} программного проекта из кэша", id); + var programProject = await cache.GetProjectFromCache(id); + if (programProject != null) + { + logger.LogInformation("Программный проект {id} был найден в кэше", id); + return programProject; + } + logger.LogInformation("Программного проекта {id} нет в кэше. Создаем программный проект", id); + programProject = ProgramProjectGenerator.GenerateProgramProject(id); + await producer.SendMessage(programProject); + logger.LogInformation("Сохраняем данные программного проекта {id} в кэш", id); + await cache.SaveProjectToCache(programProject); + return programProject; + } + catch (Exception ex) + { + logger.LogError(ex, "Произошла ошибка во время обработки программного проекта {id}.", id); + return null; + } + } +} diff --git a/ServiceApi/Generator/IGeneratorService.cs b/ServiceApi/Generator/IGeneratorService.cs new file mode 100644 index 00000000..8f63c795 --- /dev/null +++ b/ServiceApi/Generator/IGeneratorService.cs @@ -0,0 +1,17 @@ +using ServiceApi.Entities; + +namespace ServiceApi.Generator; + +/// +/// Интерфейс для запуска usecase по обработке программных проектов +/// +public interface IGeneratorService +{ + /// + /// Обработка запроса на генерации программного проекта + /// + /// Идентификатор + /// Программный проект + public Task ProcessProgramProject(int id); + +} diff --git a/ServiceApi/Generator/IProgramProjectCache.cs b/ServiceApi/Generator/IProgramProjectCache.cs new file mode 100644 index 00000000..b253ffae --- /dev/null +++ b/ServiceApi/Generator/IProgramProjectCache.cs @@ -0,0 +1,19 @@ +using ServiceApi.Entities; + +namespace ServiceApi.Generator; + +/// +/// Интерфейс для работы с кэшем проектов +/// +public interface IProgramProjectCache +{ + /// + /// Получить проект из кэша по id + /// + public Task GetProjectFromCache(int id); + + /// + /// Сохранить проект в кэш + /// + public Task SaveProjectToCache(ProgramProject programProject); +} diff --git a/ServiceApi/Generator/ProgramProjectCache.cs b/ServiceApi/Generator/ProgramProjectCache.cs new file mode 100644 index 00000000..958e2246 --- /dev/null +++ b/ServiceApi/Generator/ProgramProjectCache.cs @@ -0,0 +1,47 @@ +using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; +using ServiceApi.Entities; + +namespace ServiceApi.Generator; + +public class ProgramProjectCache(IDistributedCache cache, IConfiguration configuration, ILogger logger) : IProgramProjectCache +{ + /// + /// Время инвализации кэша + /// + private readonly TimeSpan _cacheExpiration = int.TryParse(configuration["CacheExpiration"], out var sec) + ? TimeSpan.FromSeconds(sec) + : TimeSpan.FromSeconds(3600); + + /// + /// Получить ПП из кэша по id + /// + /// Идентификатор ПП + /// Программный проект + public async Task GetProjectFromCache(int id) + { + var json = await cache.GetStringAsync(id.ToString()); + if (string.IsNullOrEmpty(json)) + { + logger.LogWarning("Не найден проект с {id} в кэше", id); + return null; + } + logger.LogInformation("Проект с {id} был найден в кэше", id); + return JsonSerializer.Deserialize(json); + } + + /// + /// Кладет ПП в кэш + /// + /// Программный проект + public async Task SaveProjectToCache(ProgramProject programProject) + { + logger.LogInformation("Проект с {id} добавлен в кэш", programProject.Id); + var json = JsonSerializer.Serialize(programProject); + await cache.SetStringAsync(programProject.Id.ToString(), json, + new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheExpiration + }); + } +} \ No newline at end of file diff --git a/ServiceApi/Generator/ProgramProjectGenerator.cs b/ServiceApi/Generator/ProgramProjectGenerator.cs new file mode 100644 index 00000000..97705815 --- /dev/null +++ b/ServiceApi/Generator/ProgramProjectGenerator.cs @@ -0,0 +1,43 @@ +using Bogus; +using ServiceApi.Entities; + +namespace ServiceApi.Generator; + +/// +/// Генератор программных проектов со случайными свойствами +/// +public static class ProgramProjectGenerator +{ + private static readonly Faker _faker = new Faker("ru") + .RuleFor(o => o.Name, f => + f.Lorem.Word() + " " + + f.Hacker.Abbreviation()) + .RuleFor(o => o.Customer, f => f.Company.CompanyName()) + .RuleFor(o => o.Manager, f => f.Name.FullName()) + .RuleFor(o => o.StartDate, f => DateOnly.FromDateTime(f.Date.Past(3, DateTime.Now))) + .RuleFor(o => o.PlanEndDate, (f, o) => DateOnly.FromDateTime(f.Date.Future(3, o.StartDate.ToDateTime(TimeOnly.MinValue)))) + .RuleFor(o => o.ActualEndDate, (f, o) => + { + DateTime end = f.Date.Between(o.StartDate.ToDateTime(TimeOnly.MinValue), o.PlanEndDate.ToDateTime(TimeOnly.MinValue)); + return end > DateTime.Now ? null : DateOnly.FromDateTime(end); + }) + .RuleFor(o => o.Budget, f => Math.Round(f.Finance.Amount(100000, 10000000), 2)) + .RuleFor(o => o.PercentComplete, (f, o) => o.ActualEndDate != null ? 100 : f.Random.Number(0, 99)) + .RuleFor(o => o.ActualCost, (f, o) => + { + var scatter = Convert.ToInt32(o.Budget) / 10; + return Math.Round((o.Budget - f.Finance.Amount(-scatter, scatter)) * o.PercentComplete / 100, 2); + }); + + /// + /// Метод генерации ПП + /// + /// Идентификатор ПП + /// Программный проект + public static ProgramProject GenerateProgramProject(int id) + { + var project = _faker.Generate(); + project.Id = id; + return project; + } +} \ No newline at end of file diff --git a/ServiceApi/Messaging/IProducerService.cs b/ServiceApi/Messaging/IProducerService.cs new file mode 100644 index 00000000..9190d284 --- /dev/null +++ b/ServiceApi/Messaging/IProducerService.cs @@ -0,0 +1,15 @@ +using ServiceApi.Entities; + +namespace ServiceApi.Messaging; + +/// +/// Интерфейс службы для отправки сгенерированных программных проектов в брокер сообщений +/// +public interface IProducerService +{ + /// + /// Отправляет сообщение в брокер + /// + /// Программный проект + public Task SendMessage(ProgramProject programProject); +} diff --git a/ServiceApi/Messaging/SqsProducerService.cs b/ServiceApi/Messaging/SqsProducerService.cs new file mode 100644 index 00000000..5550a328 --- /dev/null +++ b/ServiceApi/Messaging/SqsProducerService.cs @@ -0,0 +1,36 @@ +using Amazon.SQS; +using ServiceApi.Entities; +using System.Net; +using System.Text.Json; + +namespace ServiceApi.Messaging; + +/// +/// Служба для отправки сообщений в SQS +/// +/// Клиент SQS +/// Конфигурация +/// Логгер +public class SqsProducerService(IAmazonSQS client, IConfiguration configuration, ILogger logger) : IProducerService +{ + private readonly string _queueName = configuration["AWS:Resources:SQSQueueName"] + ?? throw new KeyNotFoundException("SQS queue link was not found in configuration"); + + /// + public async Task SendMessage(ProgramProject programProject) + { + try + { + var json = JsonSerializer.Serialize(programProject); + var response = await client.SendMessageAsync(_queueName, json); + if (response.HttpStatusCode == HttpStatusCode.OK) + logger.LogInformation("Программный проект {id} отправлен в очередь SQS", programProject.Id); + else + throw new Exception($"SQS вернул {response.HttpStatusCode}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Не удалось отправить программный проект через SQS"); + } + } +} diff --git a/ServiceApi/Program.cs b/ServiceApi/Program.cs new file mode 100644 index 00000000..4a13a349 --- /dev/null +++ b/ServiceApi/Program.cs @@ -0,0 +1,22 @@ +using Amazon.SQS; +using LocalStack.Client.Extensions; +using ServiceApi.Generator; +using ServiceApi.Messaging; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("RedisCache"); + +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddScoped(); + +var app = builder.Build(); +app.MapDefaultEndpoints(); + +app.MapGet("/program-project", (IGeneratorService service, int id) => service.ProcessProgramProject(id)); +app.Run(); diff --git a/ServiceApi/Properties/launchSettings.json b/ServiceApi/Properties/launchSettings.json new file mode 100644 index 00000000..5492340d --- /dev/null +++ b/ServiceApi/Properties/launchSettings.json @@ -0,0 +1,13 @@ +{ + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/ServiceApi/ServiceApi.csproj b/ServiceApi/ServiceApi.csproj new file mode 100644 index 00000000..ecade27b --- /dev/null +++ b/ServiceApi/ServiceApi.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + diff --git a/ServiceApi/WebApplicationBuilderExtensions.cs b/ServiceApi/WebApplicationBuilderExtensions.cs new file mode 100644 index 00000000..6471e4a4 --- /dev/null +++ b/ServiceApi/WebApplicationBuilderExtensions.cs @@ -0,0 +1,39 @@ +using Amazon.SQS; +using LocalStack.Client.Extensions; +using ServiceApi.Messaging; + +namespace ServiceApi; + +/// +/// Экстеншен для добавления различных служб в DI в зависимости от конфигурации приложения +/// +internal static class WebApplicationBuilderExtensions +{ + /// + /// Регистрирует клиентские службы для работы с брокером сообщений + /// + /// Билдер + /// Билдер + /// Если настройки не найдены + public static WebApplicationBuilder AddProducer(this WebApplicationBuilder builder) + { + builder.Services.AddLocalStack(builder.Configuration); + return builder.Configuration.GetSection("Settings")["MessageBroker"] switch + { + "SQS" => builder.AddSqsProducer(), + _ => throw new KeyNotFoundException("Invalid broker type. Expected SQS.") + }; + } + + /// + /// Регистрирует службы для работы с SQS + /// + /// Билдер + /// Билдер + private static WebApplicationBuilder AddSqsProducer(this WebApplicationBuilder builder) + { + builder.Services.AddScoped(); + builder.Services.AddAwsService(); + return builder; + } +} \ No newline at end of file diff --git a/ServiceApi/appsettings.Development.json b/ServiceApi/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/ServiceApi/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/ServiceApi/appsettings.json b/ServiceApi/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/ServiceApi/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +}