From bc4ddb59081936d1a2fef32ce045475c0fc1eb01 Mon Sep 17 00:00:00 2001 From: Airfix982 <25roter52@gmail.com> Date: Fri, 13 Feb 2026 18:33:14 +0400 Subject: [PATCH 1/4] feat: added api service, redis cache service and aspire orchestration --- Aspire/Aspire.AppHost/AppHost.cs | 13 ++ Aspire/Aspire.AppHost/Aspire.AppHost.csproj | 23 ++++ .../Properties/launchSettings.json | 29 ++++ .../appsettings.Development.json | 8 ++ Aspire/Aspire.AppHost/appsettings.json | 9 ++ .../Aspire.ServiceDefaults.csproj | 22 +++ Aspire/Aspire.ServiceDefaults/Extensions.cs | 127 ++++++++++++++++++ Client.Wasm/Components/StudentCard.razor | 6 +- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.sln | 30 +++++ Service.Api/Entity/ProgramProject.cs | 15 +++ Service.Api/Generator/ProgramProjectFaker.cs | 28 ++++ .../ProgramProjectGeneratorService.cs | 16 +++ Service.Api/Program.cs | 64 +++++++++ Service.Api/Properties/launchSettings.json | 41 ++++++ Service.Api/Redis/RedisCacheService.cs | 33 +++++ Service.Api/Service.Api.csproj | 20 +++ Service.Api/Service.Api.http | 6 + Service.Api/appsettings.Development.json | 8 ++ Service.Api/appsettings.json | 9 ++ 20 files changed, 505 insertions(+), 4 deletions(-) create mode 100644 Aspire/Aspire.AppHost/AppHost.cs create mode 100644 Aspire/Aspire.AppHost/Aspire.AppHost.csproj create mode 100644 Aspire/Aspire.AppHost/Properties/launchSettings.json create mode 100644 Aspire/Aspire.AppHost/appsettings.Development.json create mode 100644 Aspire/Aspire.AppHost/appsettings.json create mode 100644 Aspire/Aspire.ServiceDefaults/Aspire.ServiceDefaults.csproj create mode 100644 Aspire/Aspire.ServiceDefaults/Extensions.cs create mode 100644 Service.Api/Entity/ProgramProject.cs create mode 100644 Service.Api/Generator/ProgramProjectFaker.cs create mode 100644 Service.Api/Generator/ProgramProjectGeneratorService.cs create mode 100644 Service.Api/Program.cs create mode 100644 Service.Api/Properties/launchSettings.json create mode 100644 Service.Api/Redis/RedisCacheService.cs create mode 100644 Service.Api/Service.Api.csproj create mode 100644 Service.Api/Service.Api.http create mode 100644 Service.Api/appsettings.Development.json create mode 100644 Service.Api/appsettings.json diff --git a/Aspire/Aspire.AppHost/AppHost.cs b/Aspire/Aspire.AppHost/AppHost.cs new file mode 100644 index 0000000..aa03cfc --- /dev/null +++ b/Aspire/Aspire.AppHost/AppHost.cs @@ -0,0 +1,13 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("programproj-cache").WithRedisInsight(containerName: "programproj-insight"); + +var apiService = builder.AddProject("programproj-api") + .WithReference(cache) + .WithHttpHealthCheck("/health") + .WaitFor(cache); + +builder.AddProject("programproj-wasm") + .WaitFor(apiService); + +builder.Build().Run(); diff --git a/Aspire/Aspire.AppHost/Aspire.AppHost.csproj b/Aspire/Aspire.AppHost/Aspire.AppHost.csproj new file mode 100644 index 0000000..0f00fac --- /dev/null +++ b/Aspire/Aspire.AppHost/Aspire.AppHost.csproj @@ -0,0 +1,23 @@ + + + + + + Exe + net8.0 + enable + enable + 348a6352-668a-4b0d-833f-bbd1cc51ceb3 + + + + + + + + + + + + + diff --git a/Aspire/Aspire.AppHost/Properties/launchSettings.json b/Aspire/Aspire.AppHost/Properties/launchSettings.json new file mode 100644 index 0000000..59a529e --- /dev/null +++ b/Aspire/Aspire.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:17161;http://localhost:15041", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21204", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22223" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15041", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19104", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20068" + } + } + } +} diff --git a/Aspire/Aspire.AppHost/appsettings.Development.json b/Aspire/Aspire.AppHost/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Aspire/Aspire.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Aspire/Aspire.AppHost/appsettings.json b/Aspire/Aspire.AppHost/appsettings.json new file mode 100644 index 0000000..31c092a --- /dev/null +++ b/Aspire/Aspire.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/Aspire/Aspire.ServiceDefaults/Aspire.ServiceDefaults.csproj b/Aspire/Aspire.ServiceDefaults/Aspire.ServiceDefaults.csproj new file mode 100644 index 0000000..1b6e209 --- /dev/null +++ b/Aspire/Aspire.ServiceDefaults/Aspire.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/Aspire/Aspire.ServiceDefaults/Extensions.cs b/Aspire/Aspire.ServiceDefaults/Extensions.cs new file mode 100644 index 0000000..b72c875 --- /dev/null +++ b/Aspire/Aspire.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/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..11b2689 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,9 +4,9 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ + Номер №1 "Кэширование" + Вариант №42 "Название варианта" + Выполнена Кадников Николай 6513 Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index 4dda7c0..118aaa1 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "https://localhost:7170/land-plot" + "BaseAddress": "https://localhost:7262/program-proj" } \ No newline at end of file diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241..2288ddd 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,6 +5,16 @@ 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}") = "Service.Api", "Service.Api\Service.Api.csproj", "{5003CEA3-9343-45C1-B1E4-6FE43745A8D5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.AppHost", "Aspire\Aspire.AppHost\Aspire.AppHost.csproj", "{466A15CD-2DE0-4374-9653-08989D32708A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.ServiceDefaults", "Aspire\Aspire.ServiceDefaults\Aspire.ServiceDefaults.csproj", "{AD6B47E3-6C6E-420E-9803-369B1474B73F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.ApiService", "Aspire\Aspire.ApiService\Aspire.ApiService.csproj", "{B7E77CED-CABF-402E-9042-11B3EF948903}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.Web", "Aspire\Aspire.Web\Aspire.Web.csproj", "{EF33F125-28B4-4C04-B013-EC102109CED9}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +25,26 @@ 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 + {5003CEA3-9343-45C1-B1E4-6FE43745A8D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5003CEA3-9343-45C1-B1E4-6FE43745A8D5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5003CEA3-9343-45C1-B1E4-6FE43745A8D5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5003CEA3-9343-45C1-B1E4-6FE43745A8D5}.Release|Any CPU.Build.0 = Release|Any CPU + {466A15CD-2DE0-4374-9653-08989D32708A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {466A15CD-2DE0-4374-9653-08989D32708A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {466A15CD-2DE0-4374-9653-08989D32708A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {466A15CD-2DE0-4374-9653-08989D32708A}.Release|Any CPU.Build.0 = Release|Any CPU + {AD6B47E3-6C6E-420E-9803-369B1474B73F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AD6B47E3-6C6E-420E-9803-369B1474B73F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AD6B47E3-6C6E-420E-9803-369B1474B73F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AD6B47E3-6C6E-420E-9803-369B1474B73F}.Release|Any CPU.Build.0 = Release|Any CPU + {B7E77CED-CABF-402E-9042-11B3EF948903}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B7E77CED-CABF-402E-9042-11B3EF948903}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B7E77CED-CABF-402E-9042-11B3EF948903}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B7E77CED-CABF-402E-9042-11B3EF948903}.Release|Any CPU.Build.0 = Release|Any CPU + {EF33F125-28B4-4C04-B013-EC102109CED9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EF33F125-28B4-4C04-B013-EC102109CED9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EF33F125-28B4-4C04-B013-EC102109CED9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EF33F125-28B4-4C04-B013-EC102109CED9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Service.Api/Entity/ProgramProject.cs b/Service.Api/Entity/ProgramProject.cs new file mode 100644 index 0000000..3c2fdfc --- /dev/null +++ b/Service.Api/Entity/ProgramProject.cs @@ -0,0 +1,15 @@ +namespace Service.Api.Entity; + +public class ProgramProject +{ + public int Id { get; set; } + public string Name { get; set; } + public string Customer { get; set; } + public string Manager { get; set; } + public DateOnly StartDate { get; set; } + public DateOnly EndDatePlanned { get; set; } + public DateOnly? EndDateReal { get; set; } + public decimal Budget { get; set; } + public decimal SpentMoney { get; set; } + public int FinishedPerCent { get; set; } +} diff --git a/Service.Api/Generator/ProgramProjectFaker.cs b/Service.Api/Generator/ProgramProjectFaker.cs new file mode 100644 index 0000000..2e9b945 --- /dev/null +++ b/Service.Api/Generator/ProgramProjectFaker.cs @@ -0,0 +1,28 @@ +using Bogus; +using Service.Api.Entity; + +namespace Service.Api.Generator; + +public class ProgramProjectFaker : Faker +{ + public ProgramProjectFaker() : base("ru") + { + RuleFor(o => o.Name, f => f.Commerce.ProductName()); + 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(2, DateTime.Now))); + RuleFor(o => o.EndDatePlanned, (f, o) => DateOnly.FromDateTime(f.Date.Future(5, o.StartDate.ToDateTime(TimeOnly.MinValue)))); + RuleFor(o => o.EndDateReal, (f, o) => + { + DateTime end = f.Date.Between(o.StartDate.ToDateTime(TimeOnly.MinValue), o.EndDatePlanned.ToDateTime(TimeOnly.MinValue)); + return end > DateTime.Now ? null : DateOnly.FromDateTime(end); + }); + RuleFor(o => o.Budget, f => Math.Round(f.Finance.Amount(100_000, 1_000_000), 2)); + RuleFor(o => o.FinishedPerCent, (f, o) => o.EndDateReal != null ? 100 : f.Random.Number(1, 100)); + RuleFor(o => o.SpentMoney, (f, o) => + { + var spread = Convert.ToInt32(o.Budget) / 15; + return Math.Round((o.Budget - f.Finance.Amount(-spread, spread)) * o.FinishedPerCent / 100, 2); + }); + } +} diff --git a/Service.Api/Generator/ProgramProjectGeneratorService.cs b/Service.Api/Generator/ProgramProjectGeneratorService.cs new file mode 100644 index 0000000..6c17c0f --- /dev/null +++ b/Service.Api/Generator/ProgramProjectGeneratorService.cs @@ -0,0 +1,16 @@ +using Bogus; +using Service.Api.Entity; + +namespace Service.Api.Generator; + +public class ProgramProjectGeneratorService(Faker faker) +{ + private Faker _faker = faker; + + public ProgramProject GetProgramProjectInstance(int id) + { + ProgramProject programProject = _faker.Generate(); + programProject.Id = id; + return programProject; + } +} diff --git a/Service.Api/Program.cs b/Service.Api/Program.cs new file mode 100644 index 0000000..3883a3b --- /dev/null +++ b/Service.Api/Program.cs @@ -0,0 +1,64 @@ +using Bogus; +using Service.Api.Entity; +using Service.Api.Generator; +using Service.Api.Redis; +using StackExchange.Redis; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +// Add services to the container. +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + + +builder.Services.AddSingleton, ProgramProjectFaker>(); +builder.Services.AddSingleton(); + +builder.Services.AddSingleton(sp => +{ + var configuration = builder.Configuration.GetConnectionString("programproj-cache"); + if (configuration != null) return ConnectionMultiplexer.Connect(configuration); + else throw new InvalidOperationException("u should fix the redis connection"); +}); + +builder.Services.AddScoped(); + +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + policy.AllowAnyOrigin() + .AllowAnyHeader() + .AllowAnyMethod()); +}); + +var app = builder.Build(); + +app.UseCors(); + +app.MapDefaultEndpoints(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.MapGet("/program-proj", async (int id, ProgramProjectGeneratorService generatorService, RedisCacheService cs) => +{ + var key = $"project:{id}"; + var programProject = await cs.GetAsync(key); + if(programProject != null) return Results.Ok(programProject); + var newProject = generatorService.GetProgramProjectInstance(id); + await cs.SetAsync(key, newProject, TimeSpan.FromHours(12)); + return Results.Ok(newProject); +}) +.WithName("GetProgramProject") +.WithOpenApi(); + +app.Run(); diff --git a/Service.Api/Properties/launchSettings.json b/Service.Api/Properties/launchSettings.json new file mode 100644 index 0000000..f7af466 --- /dev/null +++ b/Service.Api/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:45188", + "sslPort": 44359 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5044", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7262;http://localhost:5044", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Service.Api/Redis/RedisCacheService.cs b/Service.Api/Redis/RedisCacheService.cs new file mode 100644 index 0000000..ce478ae --- /dev/null +++ b/Service.Api/Redis/RedisCacheService.cs @@ -0,0 +1,33 @@ +using System.Text.Json; +using Service.Api.Entity; +using StackExchange.Redis; + +namespace Service.Api.Redis; + +public class RedisCacheService +{ + private readonly IDatabase _db; + + public RedisCacheService(IConnectionMultiplexer redis) + { + this._db = redis.GetDatabase(); + } + + public async Task SetAsync(string key, T value, TimeSpan? expire) + { + var json = JsonSerializer.Serialize(value); + await this._db.StringSetAsync(key, json, expire); + } + + public async Task GetAsync(string key) + { + var value = await this._db.StringGetAsync(key); + if (value.IsNullOrEmpty) return default; + return JsonSerializer.Deserialize(value!); + } + + public async Task RemoveAsync(string key) + { + await this._db.KeyDeleteAsync(key); + } +} diff --git a/Service.Api/Service.Api.csproj b/Service.Api/Service.Api.csproj new file mode 100644 index 0000000..bc64433 --- /dev/null +++ b/Service.Api/Service.Api.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + diff --git a/Service.Api/Service.Api.http b/Service.Api/Service.Api.http new file mode 100644 index 0000000..2eec3c2 --- /dev/null +++ b/Service.Api/Service.Api.http @@ -0,0 +1,6 @@ +@Service.Api_HostAddress = https://localhost:7262 + +GET {{Service.Api_HostAddress}}/program-proj?id=1 +Accept: application/json + +### diff --git a/Service.Api/appsettings.Development.json b/Service.Api/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Service.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Service.Api/appsettings.json b/Service.Api/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/Service.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} From 004e4c4190a63ee6b4a95604c5f437ba845c553b Mon Sep 17 00:00:00 2001 From: Airfix982 <25roter52@gmail.com> Date: Sat, 14 Feb 2026 19:03:03 +0400 Subject: [PATCH 2/4] ref: small refactoring --- CloudDevelopment.sln | 12 ------------ Service.Api/Entity/ProgramProject.cs | 4 ++-- .../Generator/ProgramProjectGeneratorService.cs | 4 ++-- 3 files changed, 4 insertions(+), 16 deletions(-) diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index 2288ddd..4b6a66b 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -11,10 +11,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.AppHost", "Aspire\As EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.ServiceDefaults", "Aspire\Aspire.ServiceDefaults\Aspire.ServiceDefaults.csproj", "{AD6B47E3-6C6E-420E-9803-369B1474B73F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.ApiService", "Aspire\Aspire.ApiService\Aspire.ApiService.csproj", "{B7E77CED-CABF-402E-9042-11B3EF948903}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.Web", "Aspire\Aspire.Web\Aspire.Web.csproj", "{EF33F125-28B4-4C04-B013-EC102109CED9}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -37,14 +33,6 @@ Global {AD6B47E3-6C6E-420E-9803-369B1474B73F}.Debug|Any CPU.Build.0 = Debug|Any CPU {AD6B47E3-6C6E-420E-9803-369B1474B73F}.Release|Any CPU.ActiveCfg = Release|Any CPU {AD6B47E3-6C6E-420E-9803-369B1474B73F}.Release|Any CPU.Build.0 = Release|Any CPU - {B7E77CED-CABF-402E-9042-11B3EF948903}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B7E77CED-CABF-402E-9042-11B3EF948903}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B7E77CED-CABF-402E-9042-11B3EF948903}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B7E77CED-CABF-402E-9042-11B3EF948903}.Release|Any CPU.Build.0 = Release|Any CPU - {EF33F125-28B4-4C04-B013-EC102109CED9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EF33F125-28B4-4C04-B013-EC102109CED9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EF33F125-28B4-4C04-B013-EC102109CED9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EF33F125-28B4-4C04-B013-EC102109CED9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Service.Api/Entity/ProgramProject.cs b/Service.Api/Entity/ProgramProject.cs index 3c2fdfc..71594ab 100644 --- a/Service.Api/Entity/ProgramProject.cs +++ b/Service.Api/Entity/ProgramProject.cs @@ -1,8 +1,8 @@ namespace Service.Api.Entity; -public class ProgramProject +public record ProgramProject { - public int Id { get; set; } + public int Id { get; init; } public string Name { get; set; } public string Customer { get; set; } public string Manager { get; set; } diff --git a/Service.Api/Generator/ProgramProjectGeneratorService.cs b/Service.Api/Generator/ProgramProjectGeneratorService.cs index 6c17c0f..a843201 100644 --- a/Service.Api/Generator/ProgramProjectGeneratorService.cs +++ b/Service.Api/Generator/ProgramProjectGeneratorService.cs @@ -10,7 +10,7 @@ public class ProgramProjectGeneratorService(Faker faker) public ProgramProject GetProgramProjectInstance(int id) { ProgramProject programProject = _faker.Generate(); - programProject.Id = id; - return programProject; + return programProject with { Id = id }; + } } From af5e41bd41ad319a655e5a7aa508aa29c5dce6cb Mon Sep 17 00:00:00 2001 From: Airfix982 <25roter52@gmail.com> Date: Tue, 17 Feb 2026 14:49:00 +0400 Subject: [PATCH 3/4] fix: small fix --- Client.Wasm/Components/StudentCard.razor | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 11b2689..2093dbc 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -5,7 +5,7 @@ Номер №1 "Кэширование" - Вариант №42 "Название варианта" + Вариант №42 "Программный проект" Выполнена Кадников Николай 6513 Ссылка на форк From 7baab03a10bd201595a432cadd8abacec323a3fa Mon Sep 17 00:00:00 2001 From: Airfix982 <25roter52@gmail.com> Date: Thu, 19 Feb 2026 15:23:50 +0400 Subject: [PATCH 4/4] fix: added fork link, added summaries, added primary constructors instead of usual ones, removed extra methods, added Redis exceptions handling, changed cors configuration, refactored ProgramProjectGeneratorService.cs - moved all the logic into new ProgramProjectCacheService.cs + small refactoring --- Client.Wasm/Components/StudentCard.razor | 2 +- Service.Api/Entity/ProgramProject.cs | 35 ++++++++++++++- Service.Api/Generator/ProgramProjectFaker.cs | 11 ++++- .../ProgramProjectGeneratorService.cs | 16 ------- Service.Api/Program.cs | 43 ++++++++----------- Service.Api/Redis/RedisCacheService.cs | 33 +++++++------- Service.Api/Service.Api.csproj | 2 - .../Services/ProgramProjectCacheService.cs | 39 +++++++++++++++++ 8 files changed, 120 insertions(+), 61 deletions(-) delete mode 100644 Service.Api/Generator/ProgramProjectGeneratorService.cs create mode 100644 Service.Api/Services/ProgramProjectCacheService.cs diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 2093dbc..8fd30db 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -7,7 +7,7 @@ Номер №1 "Кэширование" Вариант №42 "Программный проект" Выполнена Кадников Николай 6513 - Ссылка на форк + Ссылка на форк diff --git a/Service.Api/Entity/ProgramProject.cs b/Service.Api/Entity/ProgramProject.cs index 71594ab..2147695 100644 --- a/Service.Api/Entity/ProgramProject.cs +++ b/Service.Api/Entity/ProgramProject.cs @@ -1,15 +1,48 @@ namespace Service.Api.Entity; - +/// +/// This class describes program project with customer, manager, +/// dates of start n end, budged and spent money. +/// public record ProgramProject { + /// + /// The project's ID + /// public int Id { get; init; } + /// + /// The project's name + /// public string Name { get; set; } + /// + /// The project's customer + /// public string Customer { get; set; } + /// + /// The project's manager + /// public string Manager { get; set; } + /// + /// The date of actual start of the project + /// public DateOnly StartDate { get; set; } + /// + /// The planned date of the end of project + /// public DateOnly EndDatePlanned { get; set; } + /// + /// The real date of the end of the project. It may be null if the project is still in progress. + /// public DateOnly? EndDateReal { get; set; } + /// + /// The project's budget + /// public decimal Budget { get; set; } + /// + /// How much money the project actually spent + /// public decimal SpentMoney { get; set; } + /// + /// Shows how complete the project is + /// public int FinishedPerCent { get; set; } } diff --git a/Service.Api/Generator/ProgramProjectFaker.cs b/Service.Api/Generator/ProgramProjectFaker.cs index 2e9b945..4229e3f 100644 --- a/Service.Api/Generator/ProgramProjectFaker.cs +++ b/Service.Api/Generator/ProgramProjectFaker.cs @@ -2,9 +2,16 @@ using Service.Api.Entity; namespace Service.Api.Generator; - +/// +/// Generator of test data of Program Project using Bogus. +/// public class ProgramProjectFaker : Faker { + /// + /// Initializes the ProgramProject field generation rules + /// with the "ru" locale and established dependencies between dates, + /// budget, completion percentage, and actual costs. + /// public ProgramProjectFaker() : base("ru") { RuleFor(o => o.Name, f => f.Commerce.ProductName()); @@ -18,7 +25,7 @@ public ProgramProjectFaker() : base("ru") return end > DateTime.Now ? null : DateOnly.FromDateTime(end); }); RuleFor(o => o.Budget, f => Math.Round(f.Finance.Amount(100_000, 1_000_000), 2)); - RuleFor(o => o.FinishedPerCent, (f, o) => o.EndDateReal != null ? 100 : f.Random.Number(1, 100)); + RuleFor(o => o.FinishedPerCent, (f, o) => o.EndDateReal != null ? 100 : f.Random.Number(1, 99)); RuleFor(o => o.SpentMoney, (f, o) => { var spread = Convert.ToInt32(o.Budget) / 15; diff --git a/Service.Api/Generator/ProgramProjectGeneratorService.cs b/Service.Api/Generator/ProgramProjectGeneratorService.cs deleted file mode 100644 index a843201..0000000 --- a/Service.Api/Generator/ProgramProjectGeneratorService.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Bogus; -using Service.Api.Entity; - -namespace Service.Api.Generator; - -public class ProgramProjectGeneratorService(Faker faker) -{ - private Faker _faker = faker; - - public ProgramProject GetProgramProjectInstance(int id) - { - ProgramProject programProject = _faker.Generate(); - return programProject with { Id = id }; - - } -} diff --git a/Service.Api/Program.cs b/Service.Api/Program.cs index 3883a3b..06a8f95 100644 --- a/Service.Api/Program.cs +++ b/Service.Api/Program.cs @@ -2,20 +2,16 @@ using Service.Api.Entity; using Service.Api.Generator; using Service.Api.Redis; +using Service.Api.Services; using StackExchange.Redis; var builder = WebApplication.CreateBuilder(args); builder.AddServiceDefaults(); -// Add services to the container. -// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); - builder.Services.AddSingleton, ProgramProjectFaker>(); -builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => { @@ -25,13 +21,25 @@ }); builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddCors(options => { options.AddDefaultPolicy(policy => - policy.AllowAnyOrigin() - .AllowAnyHeader() - .AllowAnyMethod()); + policy.SetIsOriginAllowed(origin => + { + try + { + var uri = new Uri(origin); + return uri.Host == "localhost"; + } + catch + { + return false; + } + }) + .WithMethods("GET") + .AllowAnyHeader()); }); var app = builder.Build(); @@ -40,25 +48,12 @@ app.MapDefaultEndpoints(); -// Configure the HTTP request pipeline. -if (app.Environment.IsDevelopment()) -{ - app.UseSwagger(); - app.UseSwaggerUI(); -} - app.UseHttpsRedirection(); -app.MapGet("/program-proj", async (int id, ProgramProjectGeneratorService generatorService, RedisCacheService cs) => +app.MapGet("/program-proj", async (int id, ProgramProjectCacheService cacheService) => { - var key = $"project:{id}"; - var programProject = await cs.GetAsync(key); - if(programProject != null) return Results.Ok(programProject); - var newProject = generatorService.GetProgramProjectInstance(id); - await cs.SetAsync(key, newProject, TimeSpan.FromHours(12)); - return Results.Ok(newProject); + return Results.Ok(await cacheService.GetOrGenerateAsync(id)); }) -.WithName("GetProgramProject") -.WithOpenApi(); +.WithName("GetProgramProject"); app.Run(); diff --git a/Service.Api/Redis/RedisCacheService.cs b/Service.Api/Redis/RedisCacheService.cs index ce478ae..7dc5937 100644 --- a/Service.Api/Redis/RedisCacheService.cs +++ b/Service.Api/Redis/RedisCacheService.cs @@ -3,31 +3,34 @@ using StackExchange.Redis; namespace Service.Api.Redis; - -public class RedisCacheService +/// +/// Provides Redis caching for storing and retrieving objects. +/// +public class RedisCacheService(IConnectionMultiplexer redis) { - private readonly IDatabase _db; - - public RedisCacheService(IConnectionMultiplexer redis) - { - this._db = redis.GetDatabase(); - } - + private readonly IDatabase _db = redis.GetDatabase(); + /// + /// Stores a value inn Redis. + /// + /// The type of the value to store. + /// Redis key. + /// Object which will be serialized and stored. + /// Expiration timespan, or null for no expiration. public async Task SetAsync(string key, T value, TimeSpan? expire) { var json = JsonSerializer.Serialize(value); await this._db.StringSetAsync(key, json, expire); } - + /// + /// Retrieves a value from Redis and deserializes it. + /// + /// The expected return typee. + /// Redis key. + /// The deserialized value, or default if the key does'nt exist. public async Task GetAsync(string key) { var value = await this._db.StringGetAsync(key); if (value.IsNullOrEmpty) return default; return JsonSerializer.Deserialize(value!); } - - public async Task RemoveAsync(string key) - { - await this._db.KeyDeleteAsync(key); - } } diff --git a/Service.Api/Service.Api.csproj b/Service.Api/Service.Api.csproj index bc64433..c398858 100644 --- a/Service.Api/Service.Api.csproj +++ b/Service.Api/Service.Api.csproj @@ -9,8 +9,6 @@ - - diff --git a/Service.Api/Services/ProgramProjectCacheService.cs b/Service.Api/Services/ProgramProjectCacheService.cs new file mode 100644 index 0000000..2d59d1c --- /dev/null +++ b/Service.Api/Services/ProgramProjectCacheService.cs @@ -0,0 +1,39 @@ +using Bogus; +using Service.Api.Entity; +using Service.Api.Generator; +using Service.Api.Redis; +using StackExchange.Redis; + +namespace Service.Api.Services; + +/// +/// Provides cached access to instances. +/// Generates a new project if it is not found in Redis. +/// +public class ProgramProjectCacheService(RedisCacheService cs, Faker faker) +{ + private RedisCacheService _cs = cs; + private Faker _faker = faker; + /// + /// Returns a cached by ID, + /// or generates and stores a new one if not found. + /// + /// Id of the project. + /// The existing or newly generated . + public async Task GetOrGenerateAsync(int id) + { + var key = $"project:{id}"; + try + { + var programProject = await _cs.GetAsync(key); + if (programProject != null) return programProject; + } + catch (RedisException ex) + { + Console.WriteLine(ex.Message); + } + ProgramProject newProject = _faker.Generate(); + await _cs.SetAsync(key, newProject, TimeSpan.FromHours(12)); + return newProject with { Id = id }; + } +}