From 6526d7172fdb94b8ffe9a7f037a15d80b934482d Mon Sep 17 00:00:00 2001 From: neygenius Date: Wed, 6 May 2026 04:44:13 +0400 Subject: [PATCH 1/4] =?UTF-8?q?=D0=92=D1=81=D1=82=D0=B0=D0=BB=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=BF=D1=83=D1=82=D1=8C=20=D0=B8=D1=81=D1=82=D0=B8?= =?UTF-8?q?=D0=BD=D1=8B=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Client.Wasm/Components/StudentCard.razor | 8 +- Client.Wasm/wwwroot/appsettings.json | 2 +- Cloud.API/Cloud.API.csproj | 19 +++ Cloud.API/Controllers/EmployeeController.cs | 39 ++++++ Cloud.API/Models/Employee.cs | 48 +++++++ Cloud.API/Program.cs | 41 ++++++ Cloud.API/Properties/launchSettings.json | 41 ++++++ Cloud.API/Services/EmployeeGenerator.cs | 63 +++++++++ Cloud.API/Services/EmployeeService.cs | 86 ++++++++++++ Cloud.API/Services/IEmployeeGenerator.cs | 15 +++ Cloud.API/Services/IEmployeeService.cs | 17 +++ Cloud.API/appsettings.Development.json | 8 ++ Cloud.API/appsettings.json | 10 ++ Cloud.AppHost/AppHost.cs | 13 ++ Cloud.AppHost/Cloud.AppHost.csproj | 21 +++ Cloud.AppHost/Properties/launchSettings.json | 31 +++++ Cloud.AppHost/appsettings.Development.json | 8 ++ Cloud.AppHost/appsettings.json | 9 ++ .../Cloud.ServiceDefaults.csproj | 23 ++++ Cloud.ServiceDefaults/Extensions.cs | 126 ++++++++++++++++++ CloudDevelopment.sln | 22 ++- 21 files changed, 643 insertions(+), 7 deletions(-) create mode 100644 Cloud.API/Cloud.API.csproj create mode 100644 Cloud.API/Controllers/EmployeeController.cs create mode 100644 Cloud.API/Models/Employee.cs create mode 100644 Cloud.API/Program.cs create mode 100644 Cloud.API/Properties/launchSettings.json create mode 100644 Cloud.API/Services/EmployeeGenerator.cs create mode 100644 Cloud.API/Services/EmployeeService.cs create mode 100644 Cloud.API/Services/IEmployeeGenerator.cs create mode 100644 Cloud.API/Services/IEmployeeService.cs create mode 100644 Cloud.API/appsettings.Development.json create mode 100644 Cloud.API/appsettings.json create mode 100644 Cloud.AppHost/AppHost.cs create mode 100644 Cloud.AppHost/Cloud.AppHost.csproj create mode 100644 Cloud.AppHost/Properties/launchSettings.json create mode 100644 Cloud.AppHost/appsettings.Development.json create mode 100644 Cloud.AppHost/appsettings.json create mode 100644 Cloud.ServiceDefaults/Cloud.ServiceDefaults.csproj create mode 100644 Cloud.ServiceDefaults/Extensions.cs diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..7061d426 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 "Кэширование" + Вариант №48 "Сотрудник компании" + Выполнена Ненашевым Дмитрием 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..afe61cc6 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7297/employee" } diff --git a/Cloud.API/Cloud.API.csproj b/Cloud.API/Cloud.API.csproj new file mode 100644 index 00000000..33d796a2 --- /dev/null +++ b/Cloud.API/Cloud.API.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/Cloud.API/Controllers/EmployeeController.cs b/Cloud.API/Controllers/EmployeeController.cs new file mode 100644 index 00000000..773370fd --- /dev/null +++ b/Cloud.API/Controllers/EmployeeController.cs @@ -0,0 +1,39 @@ +using Cloud.API.Services; +using Cloud.API.Models; +using Microsoft.AspNetCore.Mvc; + +namespace Cloud.API.Controllers; + +/// +/// Контроллер для получения сотрудника компании по id +/// +/// Сервис получения сотрудника компании +/// Логгер +[ApiController] +[Route("employee")] +public class EmployeesController( + IEmployeeService employeeService, + ILogger logger + ) : ControllerBase +{ + /// + /// Метод для получения сотрудника компании по id + /// + /// Идентификатор сотрудника + /// Информация о сотруднике компании + /// Успешное получение сотрудника компании + /// Некорректный id сотрудника + [ProducesResponseType(typeof(Employee), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)] + [HttpGet] + public async Task> GetEmployee([FromQuery] int id) + { + if (id <= 0) + return BadRequest(new { error = "Id must be a positive number" }); + + logger.LogInformation("HTTP GET /employee, id: {employeeId}", id); + + var employee = await employeeService.GetOrGenerateAsync(id); + return Ok(employee); + } +} diff --git a/Cloud.API/Models/Employee.cs b/Cloud.API/Models/Employee.cs new file mode 100644 index 00000000..3fabc4d5 --- /dev/null +++ b/Cloud.API/Models/Employee.cs @@ -0,0 +1,48 @@ +namespace Cloud.API.Models; + +/// +/// Информация о сотруднике компании +/// +public class Employee +{ + /// + /// Идентификатор сотрудника в системе + /// + public required int Id { get; set; } + /// + /// ФИО + /// + public required string FullName { get; set; } + /// + /// Должность + /// + public required string Position { get; set; } + /// + /// Отдел + /// + public required string Department { get; set; } + /// + /// Дата приема + /// + public DateOnly HireDate { get; set; } + /// + /// Зарплата + /// + public required decimal Salary { get; set; } + /// + /// Электронная почта + /// + public required string Email { get; set; } + /// + /// Номер телефона + /// + public required string PhoneNumber { get; set; } + /// + /// Индикатор увольнения + /// + public required bool IsFired { get; set; } + /// + /// Дата увольнения + /// + public DateOnly? FiredDate { get; set; } +} diff --git a/Cloud.API/Program.cs b/Cloud.API/Program.cs new file mode 100644 index 00000000..5d35a555 --- /dev/null +++ b/Cloud.API/Program.cs @@ -0,0 +1,41 @@ +using Cloud.Api.Services; +using Cloud.API.Services; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddSingleton(); +builder.Services.AddScoped(); + +builder.Services.AddCors(options => +{ + options.AddPolicy("LocalPolicy", policy => + { + policy + .AllowAnyOrigin() + .WithHeaders("Content-Type") + .WithMethods("GET"); + }); +}); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); +app.UseCors("LocalPolicy"); +app.MapControllers(); + +app.Run(); diff --git a/Cloud.API/Properties/launchSettings.json b/Cloud.API/Properties/launchSettings.json new file mode 100644 index 00000000..5704cb0e --- /dev/null +++ b/Cloud.API/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13373", + "sslPort": 44310 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5291", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7297;http://localhost:5291", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Cloud.API/Services/EmployeeGenerator.cs b/Cloud.API/Services/EmployeeGenerator.cs new file mode 100644 index 00000000..cf2de372 --- /dev/null +++ b/Cloud.API/Services/EmployeeGenerator.cs @@ -0,0 +1,63 @@ +using Bogus; +using Bogus.DataSets; +using Cloud.API.Models; +using Cloud.API.Services; + +namespace Cloud.Api.Services; + +/// +/// Генератор сотрудника по заданному id +/// +/// Логгер +public class EmployeeGenerator( + ILogger logger + ) : IEmployeeGenerator +{ + private readonly Faker _faker = new Faker("ru") + .RuleFor(e => e.Id, _ => 0) + .RuleFor(e => e.FullName, f => + { + var gender = f.PickRandom(); + var firstName = f.Name.FirstName(gender); + var lastName = f.Name.LastName(gender); + var patronymic = $"{f.Name.FirstName(Name.Gender.Male)}{(gender == Name.Gender.Male ? "ович" : "овна")}"; + return $"{lastName} {firstName} {patronymic}"; + }) + .RuleFor(e => e.Position, f => + { + var professions = new[] { "Developer", "Manager", "Analyst", "Designer", "QA" }; + var suffixes = new[] { "Junior", "Middle", "Senior", "Lead" }; + var suffix = f.PickRandom(suffixes); + var profession = f.PickRandom(professions); + return $"{suffix} {profession}"; + }) + .RuleFor(e => e.Department, f => f.Commerce.Department()) + .RuleFor(e => e.HireDate, f => DateOnly.FromDateTime(f.Date.Past(10))) + .RuleFor(e => e.Salary, (f, e) => + { + var suffix = e.Position.Split(' ')[0]; + decimal baseSalary = suffix switch + { + "Junior" => 50000, + "Middle" => 100000, + "Senior" => 150000, + "Lead" => 200000, + _ => 70000 + }; + return Math.Round(baseSalary + f.Random.Decimal(-5000, 25000), 2); + }) + .RuleFor(e => e.Email, (f, e) => f.Internet.Email(e.FullName)) + .RuleFor(e => e.PhoneNumber, f => f.Phone.PhoneNumber("+7(###)###-##-##")) + .RuleFor(e => e.IsFired, f => f.Random.Bool(0.2f)) + .RuleFor(e => e.FiredDate, (f, e) => + e.IsFired ? DateOnly.FromDateTime(f.Date.Between(e.HireDate.ToDateTime(TimeOnly.MinValue), DateTime.Now)) : null); + + /// + public Employee Generate(int id) + { + var employee = _faker.Generate(); + employee.Id = id; + logger.LogInformation("Generated employee with id {employeeId}", id); + return employee; + } +} \ No newline at end of file diff --git a/Cloud.API/Services/EmployeeService.cs b/Cloud.API/Services/EmployeeService.cs new file mode 100644 index 00000000..8532025b --- /dev/null +++ b/Cloud.API/Services/EmployeeService.cs @@ -0,0 +1,86 @@ +using Cloud.API.Models; +using Cloud.API.Services; +using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; + +namespace Cloud.Api.Services; + +/// +/// Сервис для получения сотрудника компании по id с кэшированием +/// +/// Генератор сотрудника +/// Сервис кэширования +/// Конфигурация приложения +/// Логгер +public class EmployeeService( + IEmployeeGenerator generator, + IDistributedCache cache, + IConfiguration configuration, + ILogger logger) : IEmployeeService +{ + private const string CacheKeyPrefix = "employee"; + private readonly TimeSpan _cacheTtl = TimeSpan.FromMinutes(configuration.GetValue("CacheTtlMinutes", 30)); + + /// + public async Task GetOrGenerateAsync(int id) + { + var cacheKey = $"{CacheKeyPrefix}:{id}"; + + var cached = await GetFromCache(cacheKey); + if (cached is not null) + { + return cached; + } + + logger.LogInformation("Cache miss for employee {Id}, generating new data", id); + var employee = generator.Generate(id); + await SetToCache(cacheKey, employee); + return employee; + } + + /// + /// Метод получения сотрудника из кэша + /// + /// Ключ кэша + /// + /// Сотрудник, или null в случае ошибки или отсутствия данных в кэше + /// + private async Task GetFromCache(string cacheKey) + { + try + { + var cached = await cache.GetStringAsync(cacheKey); + if (cached is null) return null; + + logger.LogInformation("Cache hit for key {CacheKey}", cacheKey); + return JsonSerializer.Deserialize(cached); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to read from cache for key {CacheKey}", cacheKey); + return null; + } + } + + /// + /// Сохранение сотрудника в кэш с обработкой ошибок при записи + /// + /// Ключ кэша + /// Сотрудник компании + private async Task SetToCache(string cacheKey, Employee employee) + { + try + { + var json = JsonSerializer.Serialize(employee); + await cache.SetStringAsync(cacheKey, json, new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheTtl + }); + logger.LogInformation("Cached employee {Id} with key {CacheKey}", employee.Id, cacheKey); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to write to cache for key {CacheKey}", cacheKey); + } + } +} \ No newline at end of file diff --git a/Cloud.API/Services/IEmployeeGenerator.cs b/Cloud.API/Services/IEmployeeGenerator.cs new file mode 100644 index 00000000..d5dbae74 --- /dev/null +++ b/Cloud.API/Services/IEmployeeGenerator.cs @@ -0,0 +1,15 @@ +using Cloud.API.Models; + +namespace Cloud.API.Services; + +/// +/// Интерфейс генератора сотрудника компании по id +/// +public interface IEmployeeGenerator +{ + /// + /// Генерирует сотрудника компании с указанным id + /// + /// Идентификатор сотрудника компании + public Employee Generate(int id); +} \ No newline at end of file diff --git a/Cloud.API/Services/IEmployeeService.cs b/Cloud.API/Services/IEmployeeService.cs new file mode 100644 index 00000000..9c7c9ceb --- /dev/null +++ b/Cloud.API/Services/IEmployeeService.cs @@ -0,0 +1,17 @@ +using Cloud.API.Models; + +namespace Cloud.API.Services; + +/// +/// Интерфейс сервис для получения сотрудника компании по id с кэшированием +/// +public interface IEmployeeService +{ + /// + /// Получпет сотрудника компании по id. Если сотрудник не найден, + /// то создает нового с данным id и сохраняет его в кэше + /// + /// Идентификатор сотрудника компании + /// + public Task GetOrGenerateAsync(int id); +} diff --git a/Cloud.API/appsettings.Development.json b/Cloud.API/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Cloud.API/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Cloud.API/appsettings.json b/Cloud.API/appsettings.json new file mode 100644 index 00000000..2d053cce --- /dev/null +++ b/Cloud.API/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "CacheTtlMinutes": 15 +} diff --git a/Cloud.AppHost/AppHost.cs b/Cloud.AppHost/AppHost.cs new file mode 100644 index 00000000..7a7281a5 --- /dev/null +++ b/Cloud.AppHost/AppHost.cs @@ -0,0 +1,13 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisInsight(containerName: "redis-insight"); + +var api = builder.AddProject("api") + .WithReference(redis) + .WaitFor(redis); + +var client = builder.AddProject("client") + .WaitFor(api); + +builder.Build().Run(); diff --git a/Cloud.AppHost/Cloud.AppHost.csproj b/Cloud.AppHost/Cloud.AppHost.csproj new file mode 100644 index 00000000..d5af025a --- /dev/null +++ b/Cloud.AppHost/Cloud.AppHost.csproj @@ -0,0 +1,21 @@ + + + + Exe + net8.0 + enable + enable + 8ba2b54b-4ef9-4e56-9f8f-d0397cc693b5 + + + + + + + + + + + + + diff --git a/Cloud.AppHost/Properties/launchSettings.json b/Cloud.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..c9c7dc2b --- /dev/null +++ b/Cloud.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:17080;http://localhost:15004", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21117", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23081", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22239" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15004", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19208", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18038", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20234" + } + } + } +} diff --git a/Cloud.AppHost/appsettings.Development.json b/Cloud.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Cloud.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Cloud.AppHost/appsettings.json b/Cloud.AppHost/appsettings.json new file mode 100644 index 00000000..31c092aa --- /dev/null +++ b/Cloud.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/Cloud.ServiceDefaults/Cloud.ServiceDefaults.csproj b/Cloud.ServiceDefaults/Cloud.ServiceDefaults.csproj new file mode 100644 index 00000000..c66ef377 --- /dev/null +++ b/Cloud.ServiceDefaults/Cloud.ServiceDefaults.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + + diff --git a/Cloud.ServiceDefaults/Extensions.cs b/Cloud.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..f1b21c13 --- /dev/null +++ b/Cloud.ServiceDefaults/Extensions.cs @@ -0,0 +1,126 @@ +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/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..ffcdf540 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.5.11723.231 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}") = "Cloud.ServiceDefaults", "Cloud.ServiceDefaults\Cloud.ServiceDefaults.csproj", "{3E5DBFF7-87A5-4A49-B972-0213375B5DBB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cloud.API", "Cloud.API\Cloud.API.csproj", "{1AB2AD5D-A163-E9E2-9F67-03C98B44D46C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cloud.AppHost", "Cloud.AppHost\Cloud.AppHost.csproj", "{111D7662-EE9A-4AEC-9299-16A0239072CB}" +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 + {3E5DBFF7-87A5-4A49-B972-0213375B5DBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3E5DBFF7-87A5-4A49-B972-0213375B5DBB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3E5DBFF7-87A5-4A49-B972-0213375B5DBB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3E5DBFF7-87A5-4A49-B972-0213375B5DBB}.Release|Any CPU.Build.0 = Release|Any CPU + {1AB2AD5D-A163-E9E2-9F67-03C98B44D46C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1AB2AD5D-A163-E9E2-9F67-03C98B44D46C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1AB2AD5D-A163-E9E2-9F67-03C98B44D46C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1AB2AD5D-A163-E9E2-9F67-03C98B44D46C}.Release|Any CPU.Build.0 = Release|Any CPU + {111D7662-EE9A-4AEC-9299-16A0239072CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {111D7662-EE9A-4AEC-9299-16A0239072CB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {111D7662-EE9A-4AEC-9299-16A0239072CB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {111D7662-EE9A-4AEC-9299-16A0239072CB}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 8f77cd5df6dc0d139dbe1ef28bd355816e07913d Mon Sep 17 00:00:00 2001 From: neygenius Date: Wed, 6 May 2026 16:20:53 +0400 Subject: [PATCH 2/4] =?UTF-8?q?=D0=B2=D0=BD=D0=B5=D1=81=20=D0=BF=D1=80?= =?UTF-8?q?=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Client.Wasm/Client.Wasm.csproj | 6 ++-- Cloud.API/Cloud.API.csproj | 2 +- Cloud.API/Services/EmployeeGenerator.cs | 36 +++++++++---------- Cloud.API/Services/EmployeeService.cs | 4 +-- Cloud.API/appsettings.json | 1 + Cloud.AppHost/Cloud.AppHost.csproj | 6 ++-- .../Cloud.ServiceDefaults.csproj | 4 +-- CloudDevelopment.slnx | 6 ++++ 8 files changed, 34 insertions(+), 31 deletions(-) create mode 100644 CloudDevelopment.slnx diff --git a/Client.Wasm/Client.Wasm.csproj b/Client.Wasm/Client.Wasm.csproj index 0ba9f90c..66634ea4 100644 --- a/Client.Wasm/Client.Wasm.csproj +++ b/Client.Wasm/Client.Wasm.csproj @@ -1,7 +1,7 @@  - net8.0 + net10.0 enable enable @@ -14,8 +14,8 @@ - - + + diff --git a/Cloud.API/Cloud.API.csproj b/Cloud.API/Cloud.API.csproj index 33d796a2..03262b1b 100644 --- a/Cloud.API/Cloud.API.csproj +++ b/Cloud.API/Cloud.API.csproj @@ -1,7 +1,7 @@ - net8.0 + net10.0 enable enable diff --git a/Cloud.API/Services/EmployeeGenerator.cs b/Cloud.API/Services/EmployeeGenerator.cs index cf2de372..bd969af2 100644 --- a/Cloud.API/Services/EmployeeGenerator.cs +++ b/Cloud.API/Services/EmployeeGenerator.cs @@ -13,37 +13,33 @@ public class EmployeeGenerator( ILogger logger ) : IEmployeeGenerator { + private static readonly string[] _professions = { "Developer", "Manager", "Analyst", "Designer", "QA" }; + private static readonly string[] _suffixes = { "Junior", "Middle", "Senior", "Lead" }; + + private static readonly Dictionary _baseSalaryBySuffix = new() + { + ["Junior"] = 50000, + ["Middle"] = 100000, + ["Senior"] = 150000, + ["Lead"] = 200000 + }; + private readonly Faker _faker = new Faker("ru") .RuleFor(e => e.Id, _ => 0) .RuleFor(e => e.FullName, f => { var gender = f.PickRandom(); - var firstName = f.Name.FirstName(gender); - var lastName = f.Name.LastName(gender); - var patronymic = $"{f.Name.FirstName(Name.Gender.Male)}{(gender == Name.Gender.Male ? "ович" : "овна")}"; - return $"{lastName} {firstName} {patronymic}"; - }) - .RuleFor(e => e.Position, f => - { - var professions = new[] { "Developer", "Manager", "Analyst", "Designer", "QA" }; - var suffixes = new[] { "Junior", "Middle", "Senior", "Lead" }; - var suffix = f.PickRandom(suffixes); - var profession = f.PickRandom(professions); - return $"{suffix} {profession}"; + return $"{f.Name.LastName(gender)} {f.Name.FirstName(gender)} " + + $"{f.Name.FirstName(Name.Gender.Male)}{(gender == Name.Gender.Male ? "ович" : "овна")}"; + }) + .RuleFor(e => e.Position, f => $"{f.PickRandom(_suffixes)} {f.PickRandom(_professions)}") .RuleFor(e => e.Department, f => f.Commerce.Department()) .RuleFor(e => e.HireDate, f => DateOnly.FromDateTime(f.Date.Past(10))) .RuleFor(e => e.Salary, (f, e) => { var suffix = e.Position.Split(' ')[0]; - decimal baseSalary = suffix switch - { - "Junior" => 50000, - "Middle" => 100000, - "Senior" => 150000, - "Lead" => 200000, - _ => 70000 - }; + var baseSalary = _baseSalaryBySuffix.GetValueOrDefault(suffix, 70000); return Math.Round(baseSalary + f.Random.Decimal(-5000, 25000), 2); }) .RuleFor(e => e.Email, (f, e) => f.Internet.Email(e.FullName)) diff --git a/Cloud.API/Services/EmployeeService.cs b/Cloud.API/Services/EmployeeService.cs index 8532025b..fa47004a 100644 --- a/Cloud.API/Services/EmployeeService.cs +++ b/Cloud.API/Services/EmployeeService.cs @@ -18,13 +18,13 @@ public class EmployeeService( IConfiguration configuration, ILogger logger) : IEmployeeService { - private const string CacheKeyPrefix = "employee"; + private readonly string _cacheKeyPrefix = configuration.GetValue("CacheKeyPrefix", "employee"); private readonly TimeSpan _cacheTtl = TimeSpan.FromMinutes(configuration.GetValue("CacheTtlMinutes", 30)); /// public async Task GetOrGenerateAsync(int id) { - var cacheKey = $"{CacheKeyPrefix}:{id}"; + var cacheKey = $"{_cacheKeyPrefix}:{id}"; var cached = await GetFromCache(cacheKey); if (cached is not null) diff --git a/Cloud.API/appsettings.json b/Cloud.API/appsettings.json index 2d053cce..1a7f697b 100644 --- a/Cloud.API/appsettings.json +++ b/Cloud.API/appsettings.json @@ -6,5 +6,6 @@ } }, "AllowedHosts": "*", + "CacheKeyPrefix": "employee", "CacheTtlMinutes": 15 } diff --git a/Cloud.AppHost/Cloud.AppHost.csproj b/Cloud.AppHost/Cloud.AppHost.csproj index d5af025a..d6584c3c 100644 --- a/Cloud.AppHost/Cloud.AppHost.csproj +++ b/Cloud.AppHost/Cloud.AppHost.csproj @@ -2,15 +2,15 @@ Exe - net8.0 + net10.0 enable enable 8ba2b54b-4ef9-4e56-9f8f-d0397cc693b5 - - + + diff --git a/Cloud.ServiceDefaults/Cloud.ServiceDefaults.csproj b/Cloud.ServiceDefaults/Cloud.ServiceDefaults.csproj index c66ef377..aafd57a7 100644 --- a/Cloud.ServiceDefaults/Cloud.ServiceDefaults.csproj +++ b/Cloud.ServiceDefaults/Cloud.ServiceDefaults.csproj @@ -1,7 +1,7 @@ - + - net8.0 + net10.0 enable enable true diff --git a/CloudDevelopment.slnx b/CloudDevelopment.slnx new file mode 100644 index 00000000..2e43695a --- /dev/null +++ b/CloudDevelopment.slnx @@ -0,0 +1,6 @@ + + + + + + From e4e6fa8a7ab54d33e8a579c8c25f4e51789bcd3d Mon Sep 17 00:00:00 2001 From: neygenius Date: Wed, 6 May 2026 16:39:46 +0400 Subject: [PATCH 3/4] =?UTF-8?q?=D0=BF=D0=BE=D0=B4=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BF=D0=BE=D0=BB=D0=B8=D1=82=D0=B8=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cloud.API/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cloud.API/Program.cs b/Cloud.API/Program.cs index 5d35a555..28785b39 100644 --- a/Cloud.API/Program.cs +++ b/Cloud.API/Program.cs @@ -18,7 +18,7 @@ options.AddPolicy("LocalPolicy", policy => { policy - .AllowAnyOrigin() + .SetIsOriginAllowed(origin => origin.StartsWith("https://localhost")) .WithHeaders("Content-Type") .WithMethods("GET"); }); From 6bb756ab3ac1a0b38cf5a2e72694117cb556e210 Mon Sep 17 00:00:00 2001 From: neygenius Date: Wed, 6 May 2026 17:11:52 +0400 Subject: [PATCH 4/4] =?UTF-8?q?=D0=B8=D0=B7=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=D1=81=D1=8F=20=D0=BE=D1=82=20=D0=BB=D0=B8=D1=88=D0=BD=D0=B5?= =?UTF-8?q?=D0=B3=D0=BE=20=D0=BC=D0=B0=D1=81=D1=81=D0=B8=D0=B2=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cloud.API/Services/EmployeeGenerator.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Cloud.API/Services/EmployeeGenerator.cs b/Cloud.API/Services/EmployeeGenerator.cs index bd969af2..6e2a2444 100644 --- a/Cloud.API/Services/EmployeeGenerator.cs +++ b/Cloud.API/Services/EmployeeGenerator.cs @@ -14,7 +14,6 @@ ILogger logger ) : IEmployeeGenerator { private static readonly string[] _professions = { "Developer", "Manager", "Analyst", "Designer", "QA" }; - private static readonly string[] _suffixes = { "Junior", "Middle", "Senior", "Lead" }; private static readonly Dictionary _baseSalaryBySuffix = new() { @@ -33,7 +32,7 @@ ILogger logger $"{f.Name.FirstName(Name.Gender.Male)}{(gender == Name.Gender.Male ? "ович" : "овна")}"; }) - .RuleFor(e => e.Position, f => $"{f.PickRandom(_suffixes)} {f.PickRandom(_professions)}") + .RuleFor(e => e.Position, f => $"{f.PickRandom(_baseSalaryBySuffix.Keys.ToArray())} {f.PickRandom(_professions)}") .RuleFor(e => e.Department, f => f.Commerce.Department()) .RuleFor(e => e.HireDate, f => DateOnly.FromDateTime(f.Date.Past(10))) .RuleFor(e => e.Salary, (f, e) =>