diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..b36a63c9 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 "Кэширование" + Вариант №34 "Программный проект" + Выполнена Сысолятиным Егором 6512 + Ссылка на форк diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..99b0b5c8 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -1,10 +1,16 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.14.36811.4 +# Visual Studio Version 18 +VisualStudioVersion = 18.4.11626.88 stable 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}") = "CloudDevelopment.AppHost", "CloudDevelopment\CloudDevelopment.AppHost\CloudDevelopment.AppHost.csproj", "{3505653B-9833-43DD-8E51-1D359D201914}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.ServiceDefaults", "CloudDevelopment\CloudDevelopment.ServiceDefaults\CloudDevelopment.ServiceDefaults.csproj", "{18868854-E44C-A570-242C-63484B3BC379}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GenerationService", "GenerationService\GenerationService.csproj", "{34140EB6-F1B4-5A29-B45A-DBC1635966E5}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +21,18 @@ 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 + {3505653B-9833-43DD-8E51-1D359D201914}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3505653B-9833-43DD-8E51-1D359D201914}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3505653B-9833-43DD-8E51-1D359D201914}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3505653B-9833-43DD-8E51-1D359D201914}.Release|Any CPU.Build.0 = Release|Any CPU + {18868854-E44C-A570-242C-63484B3BC379}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {18868854-E44C-A570-242C-63484B3BC379}.Debug|Any CPU.Build.0 = Debug|Any CPU + {18868854-E44C-A570-242C-63484B3BC379}.Release|Any CPU.ActiveCfg = Release|Any CPU + {18868854-E44C-A570-242C-63484B3BC379}.Release|Any CPU.Build.0 = Release|Any CPU + {34140EB6-F1B4-5A29-B45A-DBC1635966E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {34140EB6-F1B4-5A29-B45A-DBC1635966E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {34140EB6-F1B4-5A29-B45A-DBC1635966E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {34140EB6-F1B4-5A29-B45A-DBC1635966E5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CloudDevelopment/CloudDevelopment.AppHost/AppHost.cs b/CloudDevelopment/CloudDevelopment.AppHost/AppHost.cs new file mode 100644 index 00000000..97e9875f --- /dev/null +++ b/CloudDevelopment/CloudDevelopment.AppHost/AppHost.cs @@ -0,0 +1,14 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisInsight(); + +var generation = builder.AddProject("generation-service") + .WithReference(redis) + .WaitFor(redis); + +builder.AddProject("client-wasm") + .WithReference(generation) + .WaitFor(generation); + +builder.Build().Run(); \ No newline at end of file diff --git a/CloudDevelopment/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj b/CloudDevelopment/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj new file mode 100644 index 00000000..b28e057f --- /dev/null +++ b/CloudDevelopment/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj @@ -0,0 +1,17 @@ + + + + Exe + net8.0 + enable + enable + 40038ea2-2aa4-401d-a7e5-218c78b6c0c5 + + + + + + + + + diff --git a/CloudDevelopment/CloudDevelopment.AppHost/Properties/launchSettings.json b/CloudDevelopment/CloudDevelopment.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..cae9441e --- /dev/null +++ b/CloudDevelopment/CloudDevelopment.AppHost/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17149;http://localhost:15072", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21077", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23195", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22234" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15072", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19047", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18197", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20205" + } + } + } +} diff --git a/CloudDevelopment/CloudDevelopment.AppHost/appsettings.Development.json b/CloudDevelopment/CloudDevelopment.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CloudDevelopment/CloudDevelopment.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CloudDevelopment/CloudDevelopment.AppHost/appsettings.json b/CloudDevelopment/CloudDevelopment.AppHost/appsettings.json new file mode 100644 index 00000000..31c092aa --- /dev/null +++ b/CloudDevelopment/CloudDevelopment.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CloudDevelopment/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj b/CloudDevelopment/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj new file mode 100644 index 00000000..b7140ed1 --- /dev/null +++ b/CloudDevelopment/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/CloudDevelopment/CloudDevelopment.ServiceDefaults/Extensions.cs b/CloudDevelopment/CloudDevelopment.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..b72c8753 --- /dev/null +++ b/CloudDevelopment/CloudDevelopment.ServiceDefaults/Extensions.cs @@ -0,0 +1,127 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.ServiceDiscovery; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace Microsoft.Extensions.Hosting; + +// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// This project should be referenced by each service project in your solution. +// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults +public static class Extensions +{ + private const string HealthEndpointPath = "/health"; + private const string AlivenessEndpointPath = "/alive"; + + public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.ConfigureOpenTelemetry(); + + builder.AddDefaultHealthChecks(); + + builder.Services.AddServiceDiscovery(); + + builder.Services.ConfigureHttpClientDefaults(http => + { + // Turn on resilience by default + http.AddStandardResilienceHandler(); + + // Turn on service discovery by default + http.AddServiceDiscovery(); + }); + + // Uncomment the following to restrict the allowed schemes for service discovery. + // builder.Services.Configure(options => + // { + // options.AllowedSchemes = ["https"]; + // }); + + return builder; + } + + public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddSource(builder.Environment.ApplicationName) + .AddAspNetCoreInstrumentation(tracing => + // Exclude health check requests from tracing + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) + //.AddGrpcClientInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package) + //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"])) + //{ + // builder.Services.AddOpenTelemetry() + // .UseAzureMonitor(); + //} + + return builder; + } + + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Services.AddHealthChecks() + // Add a default liveness check to ensure app is responsive + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + // Adding health checks endpoints to applications in non-development environments has security implications. + // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments. + if (app.Environment.IsDevelopment()) + { + // All health checks must pass for app to be considered ready to accept traffic after starting + app.MapHealthChecks(HealthEndpointPath); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} diff --git a/GenerationService/GenerationService.csproj b/GenerationService/GenerationService.csproj new file mode 100644 index 00000000..91e25d86 --- /dev/null +++ b/GenerationService/GenerationService.csproj @@ -0,0 +1,24 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + + + diff --git a/GenerationService/Models/SoftwareProjectContract.cs b/GenerationService/Models/SoftwareProjectContract.cs new file mode 100644 index 00000000..1156344d --- /dev/null +++ b/GenerationService/Models/SoftwareProjectContract.cs @@ -0,0 +1,25 @@ +namespace GenerationService.Models; + + +public record SoftwareProjectContract( + + int Id, + /// Название проекта + string ProjectName, + /// Заказчик проекта + string ClientCompany, + /// ФИО менеджера проекта + string ProjectManager, + /// Дата начала + DateOnly StartDate, + /// Плановая дата завершения + DateOnly PlannedEndDate, + /// Фактическая дата завершения (null если проект не завершён) + DateOnly? ActualEndDate, + /// Бюджет + decimal Budget, + /// Фактические затраты + decimal ActualCost, + /// Процент выполнения от 0 до 100 + int CompletionPercentage +); \ No newline at end of file diff --git a/GenerationService/Program.cs b/GenerationService/Program.cs new file mode 100644 index 00000000..0321135b --- /dev/null +++ b/GenerationService/Program.cs @@ -0,0 +1,53 @@ +using GenerationService.Services; +using Serilog; +using Serilog.Formatting.Compact; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Host.UseSerilog((context, configuration) => + configuration + .ReadFrom.Configuration(context.Configuration) + .WriteTo.Console(new CompactJsonFormatter())); + +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddSingleton(); +builder.Services.AddScoped(); + +// CORS — разрешаем запросы от клиента +builder.Services.AddCors(options => + options.AddDefaultPolicy(policy => + policy.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader())); + +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +var app = builder.Build(); + +app.UseCors(); +app.UseSwagger(); +app.UseSwaggerUI(); + +// GET /contracts/{id} — получить контракт по id (с кэшированием) +app.MapGet("/contracts/{id:int}", async ( + int id, + ContractCacheService cacheService) => +{ + var contract = await cacheService.GetOrCreateAsync(id); + return Results.Ok(contract); +}); + +// GET /contracts — сгенерировать случайный контракт +app.MapGet("/contracts", (ContractGeneratorService generator) => +{ + var contract = generator.Generate(Random.Shared.Next(1, 100000)); + return Results.Ok(contract); +}); + +app.MapDefaultEndpoints(); + +app.Run(); \ No newline at end of file diff --git a/GenerationService/Properties/launchSettings.json b/GenerationService/Properties/launchSettings.json new file mode 100644 index 00000000..073f933e --- /dev/null +++ b/GenerationService/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:8827", + "sslPort": 44304 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5229", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7130;http://localhost:5229", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/GenerationService/Services/ContractCacheService.cs b/GenerationService/Services/ContractCacheService.cs new file mode 100644 index 00000000..f5bc4d2f --- /dev/null +++ b/GenerationService/Services/ContractCacheService.cs @@ -0,0 +1,67 @@ +using System.Text.Json; +using GenerationService.Models; +using Microsoft.Extensions.Caching.Distributed; + +namespace GenerationService.Services; + +/// +/// Сервис кэширования контрактов через Redis +/// +public class ContractCacheService +{ + private readonly IDistributedCache _cache; + private readonly ContractGeneratorService _generator; + private readonly ILogger _logger; + + private static readonly DistributedCacheEntryOptions _cacheOptions = new() + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) + }; + + public ContractCacheService( + IDistributedCache cache, + ContractGeneratorService generator, + ILogger logger) + { + _cache = cache; + _generator = generator; + _logger = logger; + } + + public async Task GetOrCreateAsync(int id) + { + var cacheKey = $"contract:{id}"; + + try + { + var cached = await _cache.GetStringAsync(cacheKey); + if (cached is not null) + { + _logger.LogInformation("Cache HIT для ключа {CacheKey}", cacheKey); + return JsonSerializer.Deserialize(cached)!; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка чтения из кэша для ключа {CacheKey}", cacheKey); + } + + _logger.LogInformation("Cache MISS для ключа {CacheKey}. Генерация...", cacheKey); + var contract = _generator.Generate(id); + + try + { + await _cache.SetStringAsync( + cacheKey, + JsonSerializer.Serialize(contract), + _cacheOptions); + _logger.LogInformation("Контракт {Id} сохранён в кэш", id); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка записи в кэш для ключа {CacheKey}", cacheKey); + } + + return contract; + } +} \ No newline at end of file diff --git a/GenerationService/Services/ContractGeneratorService.cs b/GenerationService/Services/ContractGeneratorService.cs new file mode 100644 index 00000000..9019c5c5 --- /dev/null +++ b/GenerationService/Services/ContractGeneratorService.cs @@ -0,0 +1,48 @@ +using Bogus; +using GenerationService.Models; + +namespace GenerationService.Services; + +public class ContractGeneratorService +{ + private readonly Faker _faker = new("ru"); + + // Id теперь принимается снаружи (от пользователя) + public SoftwareProjectContract Generate(int id) + { + var startDate = DateOnly.FromDateTime(_faker.Date.Past(2)); + var plannedEnd = startDate.AddDays(_faker.Random.Int(30, 365)); + + // Процент выполнения — случайное число от 0 до 100 + var completion = _faker.Random.Int(0, 100); + + // Фактическая дата завершения — только если проект завершён (100%) + DateOnly? actualEnd = completion == 100 + ? startDate.AddDays(_faker.Random.Int(30, 400)) + : null; + + var budget = Math.Round(_faker.Finance.Amount(500_000, 10_000_000), 2); + var ratio = _faker.Random.Decimal(0.5m, 1.3m); + var actualCost = Math.Round(budget * ratio, 2); + + // ФИО: фамилия мужская + имя мужское + отчество мужское + var lastName = _faker.Name.LastName(Bogus.DataSets.Name.Gender.Male); + var firstName = _faker.Name.FirstName(Bogus.DataSets.Name.Gender.Male); + var middleName = _faker.Name.FirstName(Bogus.DataSets.Name.Gender.Male) + "ович"; + + return new SoftwareProjectContract( + Id: id, + ProjectName: _faker.Commerce.ProductName() + " " + + _faker.Hacker.Noun() + " " + + _faker.Finance.Currency().Description, + ClientCompany: _faker.Company.CompanyName(), + ProjectManager: $"{lastName} {firstName} {middleName}", + StartDate: startDate, + PlannedEndDate: plannedEnd, + ActualEndDate: actualEnd, + Budget: budget, + ActualCost: actualCost, + CompletionPercentage: completion + ); + } +} \ No newline at end of file diff --git a/GenerationService/appsettings.Development.json b/GenerationService/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/GenerationService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/GenerationService/appsettings.json b/GenerationService/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/GenerationService/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/screenshots_cloud/all_run.png b/screenshots_cloud/all_run.png new file mode 100644 index 00000000..11cf6b0b Binary files /dev/null and b/screenshots_cloud/all_run.png differ diff --git a/screenshots_cloud/localhost_run.png b/screenshots_cloud/localhost_run.png new file mode 100644 index 00000000..adacedbb Binary files /dev/null and b/screenshots_cloud/localhost_run.png differ diff --git a/screenshots_cloud/localhost_up.png b/screenshots_cloud/localhost_up.png new file mode 100644 index 00000000..9e13046e Binary files /dev/null and b/screenshots_cloud/localhost_up.png differ diff --git a/screenshots_cloud/rediska.png b/screenshots_cloud/rediska.png new file mode 100644 index 00000000..1d428cd6 Binary files /dev/null and b/screenshots_cloud/rediska.png differ