diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor
index 661f118..4158ced 100644
--- a/Client.Wasm/Components/StudentCard.razor
+++ b/Client.Wasm/Components/StudentCard.razor
@@ -4,10 +4,10 @@
- Номер №X "Название лабораторной"
- Вариант №Х "Название варианта"
- Выполнена Фамилией Именем 65ХХ
- Ссылка на форк
+ Номер №1 "«Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов"
+ Вариант №41 "Кредитная заявка "
+ Выполнена Кадниковым Егором 6513
+ Ссылка на форк
diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json
index 4dda7c0..13f5dcd 100644
--- a/Client.Wasm/wwwroot/appsettings.json
+++ b/Client.Wasm/wwwroot/appsettings.json
@@ -1,10 +1,10 @@
{
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft.AspNetCore": "Warning"
- }
- },
- "AllowedHosts": "*",
- "BaseAddress": "https://localhost:7170/land-plot"
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*",
+ "BaseAddress": "https://localhost:7240/credit-orders"
}
\ No newline at end of file
diff --git a/CloudDevelopment.AppHost/AppHost.cs b/CloudDevelopment.AppHost/AppHost.cs
new file mode 100644
index 0000000..9d824f5
--- /dev/null
+++ b/CloudDevelopment.AppHost/AppHost.cs
@@ -0,0 +1,16 @@
+using Projects;
+
+var builder = DistributedApplication.CreateBuilder(args);
+
+var cache = builder.AddRedis("credit-order-cache")
+ .WithRedisInsight(containerName: "credit-order-insight");
+
+var generator = builder.AddProject("generator")
+ .WithReference(cache, "RedisCache")
+ .WaitFor(cache);
+
+var client = builder.AddProject("credit-order-wasm")
+ .WithReference(generator)
+ .WaitFor(generator);
+
+builder.Build().Run();
diff --git a/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj
new file mode 100644
index 0000000..8269821
--- /dev/null
+++ b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj
@@ -0,0 +1,23 @@
+
+
+
+
+
+ Exe
+ net8.0
+ enable
+ enable
+ 2f419979-4dcb-43a3-bf86-3b5579f994b9
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CloudDevelopment.AppHost/Properties/launchSettings.json b/CloudDevelopment.AppHost/Properties/launchSettings.json
new file mode 100644
index 0000000..b5c6a54
--- /dev/null
+++ b/CloudDevelopment.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:17129;http://localhost:15221",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21101",
+ "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22255"
+ }
+ },
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:15221",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19083",
+ "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20274"
+ }
+ }
+ }
+}
diff --git a/CloudDevelopment.AppHost/appsettings.Development.json b/CloudDevelopment.AppHost/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/CloudDevelopment.AppHost/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/CloudDevelopment.AppHost/appsettings.json b/CloudDevelopment.AppHost/appsettings.json
new file mode 100644
index 0000000..31c092a
--- /dev/null
+++ b/CloudDevelopment.AppHost/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Aspire.Hosting.Dcp": "Warning"
+ }
+ }
+}
diff --git a/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj b/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj
new file mode 100644
index 0000000..1b6e209
--- /dev/null
+++ b/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj
@@ -0,0 +1,22 @@
+
+
+
+ net8.0
+ enable
+ enable
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CloudDevelopment.ServiceDefaults/Extensions.cs b/CloudDevelopment.ServiceDefaults/Extensions.cs
new file mode 100644
index 0000000..8b1a2b0
--- /dev/null
+++ b/CloudDevelopment.ServiceDefaults/Extensions.cs
@@ -0,0 +1,128 @@
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Diagnostics.HealthChecks;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.ServiceDiscovery;
+using OpenTelemetry;
+using OpenTelemetry.Metrics;
+using OpenTelemetry.Trace;
+
+namespace CloudDevelopment.ServiceDefaults;
+
+// 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 cb48241..514c42d 100644
--- a/CloudDevelopment.sln
+++ b/CloudDevelopment.sln
@@ -5,6 +5,12 @@ 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}") = "Generator", "Generator\Generator.csproj", "{5F162047-71C4-A730-10F2-8456E4D1F966}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.AppHost", "CloudDevelopment.AppHost\CloudDevelopment.AppHost.csproj", "{359B77C3-1D6B-4E58-A926-C907812424A8}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.ServiceDefaults", "CloudDevelopment.ServiceDefaults\CloudDevelopment.ServiceDefaults.csproj", "{DC017A15-5E73-C618-2A78-CD0D64478DC9}"
+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
+ {5F162047-71C4-A730-10F2-8456E4D1F966}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {5F162047-71C4-A730-10F2-8456E4D1F966}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {5F162047-71C4-A730-10F2-8456E4D1F966}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {5F162047-71C4-A730-10F2-8456E4D1F966}.Release|Any CPU.Build.0 = Release|Any CPU
+ {359B77C3-1D6B-4E58-A926-C907812424A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {359B77C3-1D6B-4E58-A926-C907812424A8}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {359B77C3-1D6B-4E58-A926-C907812424A8}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {359B77C3-1D6B-4E58-A926-C907812424A8}.Release|Any CPU.Build.0 = Release|Any CPU
+ {DC017A15-5E73-C618-2A78-CD0D64478DC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {DC017A15-5E73-C618-2A78-CD0D64478DC9}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {DC017A15-5E73-C618-2A78-CD0D64478DC9}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {DC017A15-5E73-C618-2A78-CD0D64478DC9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/Generator/Controllers/CreditOrderController.cs b/Generator/Controllers/CreditOrderController.cs
new file mode 100644
index 0000000..ae4c24d
--- /dev/null
+++ b/Generator/Controllers/CreditOrderController.cs
@@ -0,0 +1,37 @@
+using Generator.Dto;
+using Generator.Services;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Generator.Controllers;
+
+///
+/// HTTP API для получения кредитной заявки по идентификатору.
+/// Использует для получения данных (кэш + генерация).
+///
+[ApiController]
+[Route("credit-orders")]
+public class CreditOrderController (
+ CreditOrderService service,
+ ILogger logger
+ ) : ControllerBase
+{
+
+ ///
+ /// Возвращает кредитную заявку по из query string.
+ ///
+ /// Идентификатор заявки (должен быть больше 0).
+ /// Токен отмены запроса.
+ /// DTO кредитной заявки.
+ /// Заявка успешно получена.
+ /// Некорректный идентификатор (id <= 0).
+ [HttpGet]
+ public async Task> Get([FromQuery] int id, CancellationToken ct)
+ {
+ logger.LogInformation("HTTP GET /credit-orders requested: {OrderId}", id);
+ if (id <= 0)
+ return BadRequest("id must be greater than 0");
+ var order = await service.GetByIdAsync(id, ct);
+ logger.LogInformation("HTTP GET /credit-orders completed: {OrderId} {Status}", order.Id, order.OrderStatus);
+ return Ok(order);
+ }
+}
diff --git a/Generator/Dto/CreditOrderDto.cs b/Generator/Dto/CreditOrderDto.cs
new file mode 100644
index 0000000..23121d3
--- /dev/null
+++ b/Generator/Dto/CreditOrderDto.cs
@@ -0,0 +1,41 @@
+namespace Generator.Dto;
+
+///
+/// DTO кредитной заявки, возвращаемый HTTP API.
+///
+public class CreditOrderDto
+{
+ /// Идентификатор заявки.
+ public int Id { get; set; }
+
+ /// Тип кредита (например: Потребительский, Ипотека).
+ public string CreditType { get; set; } = "";
+
+ /// Запрошенная сумма кредита.
+ public decimal RequestedSum { get; set; }
+
+ /// Срок кредита в месяцах.
+ public int MonthsDuration { get; set; }
+
+ /// Процентная ставка (годовых).
+ public double InterestRate { get; set; }
+
+ /// Дата подачи заявки.
+ public DateOnly FilingDate { get; set; }
+
+ /// Признак необходимости страховки.
+ public bool IsInsuranceNeeded { get; set; }
+
+ /// Статус заявки: Новая / В обработке / Одобрена / Отклонена.
+ public string OrderStatus { get; set; } = "";
+
+ ///
+ /// Дата принятия решения. Заполняется только для конечных статусов (например, Одобрена/Отклонена).
+ ///
+ public DateOnly? DecisionDate { get; set; }
+
+ ///
+ /// Одобренная сумма. Заполняется только при статусе "Одобрена".
+ ///
+ public decimal? ApprovedSum { get; set; }
+}
diff --git a/Generator/Generator.csproj b/Generator/Generator.csproj
new file mode 100644
index 0000000..02ccc60
--- /dev/null
+++ b/Generator/Generator.csproj
@@ -0,0 +1,19 @@
+
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Generator/Program.cs b/Generator/Program.cs
new file mode 100644
index 0000000..b3d53ed
--- /dev/null
+++ b/Generator/Program.cs
@@ -0,0 +1,56 @@
+using CloudDevelopment.ServiceDefaults;
+using Generator.Services;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.AddServiceDefaults();
+
+builder.Services.AddControllers();
+builder.Services.AddEndpointsApiExplorer();
+builder.Services.AddSwaggerGen();
+
+builder.Services.AddCors(options =>
+{
+ options.AddDefaultPolicy(policy =>
+ policy.SetIsOriginAllowed(origin =>
+ {
+ try
+ {
+ var uri = new Uri(origin);
+ return uri.Host == "localhost";
+ }
+ catch
+ {
+ return false;
+ }
+ })
+ .WithMethods("GET")
+ .AllowAnyHeader());
+});
+
+builder.AddRedisDistributedCache(connectionName: "RedisCache");
+
+builder.Services.AddScoped();
+builder.Services.AddScoped();
+
+var app = builder.Build();
+
+app.UseCors();
+
+app.MapDefaultEndpoints();
+
+if (app.Environment.IsDevelopment())
+{
+ app.UseSwagger();
+ app.UseSwaggerUI();
+}
+
+app.UseHttpsRedirection();
+
+app.UseAuthorization();
+
+app.UseCors("wasm");
+
+app.MapControllers();
+
+app.Run();
diff --git a/Generator/Properties/launchSettings.json b/Generator/Properties/launchSettings.json
new file mode 100644
index 0000000..f60d307
--- /dev/null
+++ b/Generator/Properties/launchSettings.json
@@ -0,0 +1,41 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:6127",
+ "sslPort": 44325
+ }
+ },
+ "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:7240;http://localhost:5291",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/Generator/Services/CreditOrderGenerator.cs b/Generator/Services/CreditOrderGenerator.cs
new file mode 100644
index 0000000..d169cee
--- /dev/null
+++ b/Generator/Services/CreditOrderGenerator.cs
@@ -0,0 +1,49 @@
+using Bogus;
+using Generator.Dto;
+
+namespace Generator.Services;
+
+///
+/// Генератор псевдослучайных кредитных заявок для демо/тестирования.
+/// Включает простые зависимости между статусом и полями решения.
+///
+public class CreditOrderGenerator
+{
+ private static readonly string[] _сreditTypes = { "Потребительский", "Ипотека", "Автокредит", "Микрозайм" };
+ private static readonly string[] _statuses = { "Новая", "В обработке", "Одобрена", "Отклонена" };
+
+ ///
+ /// Генерирует кредитную заявку для заданного с реалистичными полями.
+ ///
+ /// Идентификатор заявки.
+ /// Сгенерированная заявка.
+ public CreditOrderDto Generate(int id)
+ {
+ var faker = new Faker("ru")
+ .RuleFor(x => x.Id, _ => id)
+ .RuleFor(x => x.CreditType, f => f.PickRandom(_сreditTypes))
+ .RuleFor(x => x.RequestedSum, f => Math.Round(f.Finance.Amount(1_000_000m, 100_000_000m), 2))
+ .RuleFor(x => x.MonthsDuration, f => f.Random.Int(1, 360))
+ .RuleFor(x => x.InterestRate, f => Math.Round(f.Random.Double(15.6, 20.0), 2))
+ .RuleFor(x => x.FilingDate, f => DateOnly.FromDateTime(f.Date.Past(2)))
+ .RuleFor(x => x.IsInsuranceNeeded, f => f.Random.Bool())
+ .RuleFor(x => x.OrderStatus, f => f.PickRandom(_statuses))
+ .RuleFor(x => x.DecisionDate, _ => null)
+ .RuleFor(x => x.ApprovedSum, _ => null)
+ .RuleFor(x => x.DecisionDate, (f, o) =>
+ o.OrderStatus is "Одобрена" or "Отклонена"
+ ? o.FilingDate.AddDays(f.Random.Int(0, 31))
+ : null)
+ .RuleFor(x => x.ApprovedSum, (f, o) =>
+ {
+ if (o.OrderStatus is not "Одобрена")
+ return null;
+
+ var k = f.Random.Double(0.6, 1.0);
+ var approved = o.RequestedSum * (decimal)k;
+ return Math.Round(approved, 2);
+ });
+
+ return faker.Generate();
+ }
+}
diff --git a/Generator/Services/CreditOrderService.cs b/Generator/Services/CreditOrderService.cs
new file mode 100644
index 0000000..3c1e03d
--- /dev/null
+++ b/Generator/Services/CreditOrderService.cs
@@ -0,0 +1,97 @@
+using Generator.Dto;
+using Microsoft.Extensions.Caching.Distributed;
+using System.Text.Json;
+
+namespace Generator.Services;
+
+///
+/// Сервис получения кредитной заявки по идентификатору.
+/// Сначала пытается вернуть данные из распределённого кэша, при отсутствии данных в кэше — генерирует заявку и кэширует результат.
+///
+public class CreditOrderService(
+ IDistributedCache cache,
+ CreditOrderGenerator generator,
+ IConfiguration cfg,
+ ILogger logger
+ )
+{
+
+ private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
+
+ ///
+ /// Возвращает заявку по :
+ /// 1) читает из кэша по ключу credit-order:{id};
+ /// 2) при отсутствии данных в кэше генерирует через ;
+ /// 3) сохраняет в кэш с TTL (AbsoluteExpirationRelativeToNow).
+ ///
+ /// Идентификатор заявки (должен быть больше 0).
+ /// Токен отмены.
+ /// DTO заявки.
+ /// Если <= 0.
+ /// Если запрос был отменён.
+ public async Task GetByIdAsync(int id, CancellationToken ct)
+ {
+ var ttlSeconds = cfg.GetValue("CreditOrderCache:TtlSeconds", 300);
+ if (ttlSeconds <= 0) ttlSeconds = 300;
+
+ var cacheKey = BuildCacheKey(id);
+
+ try
+ {
+ var cachedJson = await cache.GetStringAsync(cacheKey, ct);
+ if (!string.IsNullOrWhiteSpace(cachedJson))
+ {
+ var cached = JsonSerializer.Deserialize(cachedJson, _jsonOptions);
+ if (cached is not null)
+ {
+ logger.LogInformation("Cache HIT: {CacheKey} {OrderId}", cacheKey, id);
+ return cached;
+ }
+
+ logger.LogWarning("Cache DESERIALIZE FAIL: {CacheKey} {OrderId}", cacheKey, id);
+ }
+ else
+ {
+ logger.LogInformation("Cache MISS: {CacheKey} {OrderId}", cacheKey, id);
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ logger.LogInformation("Request canceled: {CacheKey} {OrderId}", cacheKey, id);
+ throw;
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(ex, "Cache READ FAIL: {CacheKey} {OrderId}", cacheKey, id);
+ }
+
+ var order = generator.Generate(id);
+
+ try
+ {
+ var cacheTtl = new DistributedCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(ttlSeconds)
+ };
+ var json = JsonSerializer.Serialize(order, _jsonOptions);
+ await cache.SetStringAsync(cacheKey, json, cacheTtl, ct);
+ logger.LogInformation("Cache SET: {CacheKey} {OrderId}", cacheKey, id);
+ }
+ catch (OperationCanceledException)
+ {
+ logger.LogInformation("Request canceled: {CacheKey} {OrderId}", cacheKey, id);
+ throw;
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(ex, "Cache WRITE FAIL: {CacheKey} {OrderId}", cacheKey, id);
+ }
+ return order;
+ }
+
+ ///
+ /// Формирует ключ кэша для заявки по идентификатору.
+ /// Формат: credit-order:{id}.
+ ///
+ private static string BuildCacheKey(int id) => $"credit-order:{id}";
+}
diff --git a/Generator/appsettings.Development.json b/Generator/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/Generator/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/Generator/appsettings.json b/Generator/appsettings.json
new file mode 100644
index 0000000..5490bdb
--- /dev/null
+++ b/Generator/appsettings.json
@@ -0,0 +1,13 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "CreditOrderCache": {
+ "Enabled": true,
+ "TtlSeconds": 60
+ },
+ "AllowedHosts": "*"
+}