diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor
index 661f118..f3d4848 100644
--- a/Client.Wasm/Components/StudentCard.razor
+++ b/Client.Wasm/Components/StudentCard.razor
@@ -4,10 +4,10 @@
- Номер №X "Название лабораторной"
- Вариант №Х "Название варианта"
- Выполнена Фамилией Именем 65ХХ
- Ссылка на форк
+ Номер №2 «Балансировка нагрузки»
+ Вариант №38 "Query Based"
+ Выполнена Елагиным Денисом 6513
+ Ссылка на форк
diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json
index d1fe7ab..7f22c19 100644
--- a/Client.Wasm/wwwroot/appsettings.json
+++ b/Client.Wasm/wwwroot/appsettings.json
@@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
- "BaseAddress": ""
+ "BaseAddress": "http://localhost:5300/residential-building"
}
diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln
index cb48241..09f502a 100644
--- a/CloudDevelopment.sln
+++ b/CloudDevelopment.sln
@@ -5,6 +5,14 @@ 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}") = "ResidentialBuilding.Generator", "ResidentialBuilding.Generator\ResidentialBuilding.Generator.csproj", "{4C3748F7-BE7B-4C97-A656-D0D467E4BC5D}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResidentialBuilding.AppHost", "ResidentialBuilding.AppHost\ResidentialBuilding.AppHost.csproj", "{248C1F9B-F012-4C7C-A458-4E2D0F918A70}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResidentialBuilding.ServiceDefaults", "ResidentialBuilding.ServiceDefaults\ResidentialBuilding.ServiceDefaults.csproj", "{3AEE6EF1-603F-411D-89C2-5CE78EBCAEBA}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResidentialBuilding.Gateway", "ResidentialBuilding.Gateway\ResidentialBuilding.Gateway.csproj", "{2CC59865-F962-47FF-9C2F-1CB6F535316B}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -15,6 +23,22 @@ 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
+ {4C3748F7-BE7B-4C97-A656-D0D467E4BC5D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {4C3748F7-BE7B-4C97-A656-D0D467E4BC5D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {4C3748F7-BE7B-4C97-A656-D0D467E4BC5D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {4C3748F7-BE7B-4C97-A656-D0D467E4BC5D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {248C1F9B-F012-4C7C-A458-4E2D0F918A70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {248C1F9B-F012-4C7C-A458-4E2D0F918A70}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {248C1F9B-F012-4C7C-A458-4E2D0F918A70}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {248C1F9B-F012-4C7C-A458-4E2D0F918A70}.Release|Any CPU.Build.0 = Release|Any CPU
+ {3AEE6EF1-603F-411D-89C2-5CE78EBCAEBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {3AEE6EF1-603F-411D-89C2-5CE78EBCAEBA}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {3AEE6EF1-603F-411D-89C2-5CE78EBCAEBA}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {3AEE6EF1-603F-411D-89C2-5CE78EBCAEBA}.Release|Any CPU.Build.0 = Release|Any CPU
+ {2CC59865-F962-47FF-9C2F-1CB6F535316B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {2CC59865-F962-47FF-9C2F-1CB6F535316B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {2CC59865-F962-47FF-9C2F-1CB6F535316B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {2CC59865-F962-47FF-9C2F-1CB6F535316B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/ResidentialBuilding.AppHost/AppHost.cs b/ResidentialBuilding.AppHost/AppHost.cs
new file mode 100644
index 0000000..6c1a875
--- /dev/null
+++ b/ResidentialBuilding.AppHost/AppHost.cs
@@ -0,0 +1,25 @@
+var builder = DistributedApplication.CreateBuilder(args);
+
+var cache = builder.AddRedis("residential-building-cache")
+ .WithRedisInsight(containerName: "residential-building-insight");
+
+var gateway = builder.AddProject("gateway")
+ .WithEndpoint("http", endpoint => endpoint.Port = 5300)
+ .WithExternalHttpEndpoints();
+
+const int generatorPortBase = 5200;
+for (var i = 1; i <= 5; ++i)
+{
+ var generator = builder.AddProject($"generator-{i}")
+ .WithReference(cache, "residential-building-cache")
+ .WithEndpoint("http", endpoint => endpoint.Port = generatorPortBase + i)
+ .WaitFor(cache);
+
+ gateway.WaitFor(generator);
+}
+
+builder.AddProject("client")
+ .WithReference(gateway)
+ .WaitFor(gateway);
+
+builder.Build().Run();
\ No newline at end of file
diff --git a/ResidentialBuilding.AppHost/Properties/launchSettings.json b/ResidentialBuilding.AppHost/Properties/launchSettings.json
new file mode 100644
index 0000000..330da1c
--- /dev/null
+++ b/ResidentialBuilding.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"
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/ResidentialBuilding.AppHost/ResidentialBuilding.AppHost.csproj b/ResidentialBuilding.AppHost/ResidentialBuilding.AppHost.csproj
new file mode 100644
index 0000000..9c51790
--- /dev/null
+++ b/ResidentialBuilding.AppHost/ResidentialBuilding.AppHost.csproj
@@ -0,0 +1,24 @@
+
+
+
+
+
+ Exe
+ net8.0
+ enable
+ enable
+ ed7e1e47-dc98-4419-8424-85412466aa9b
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/ResidentialBuilding.AppHost/appsettings.Development.json b/ResidentialBuilding.AppHost/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/ResidentialBuilding.AppHost/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/ResidentialBuilding.AppHost/appsettings.json b/ResidentialBuilding.AppHost/appsettings.json
new file mode 100644
index 0000000..31c092a
--- /dev/null
+++ b/ResidentialBuilding.AppHost/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Aspire.Hosting.Dcp": "Warning"
+ }
+ }
+}
diff --git a/ResidentialBuilding.Gateway/LoadBalancer/QueryBasedLoadBalancer.cs b/ResidentialBuilding.Gateway/LoadBalancer/QueryBasedLoadBalancer.cs
new file mode 100644
index 0000000..8967858
--- /dev/null
+++ b/ResidentialBuilding.Gateway/LoadBalancer/QueryBasedLoadBalancer.cs
@@ -0,0 +1,64 @@
+using Ocelot.LoadBalancer.Interfaces;
+using Ocelot.Responses;
+using Ocelot.Values;
+
+namespace ResidentialBuilding.Gateway.LoadBalancer;
+
+///
+/// Query-based балансировщик нагрузки для Ocelot.
+/// Выбирает downstream-сервис на основе query-параметра id запроса.
+///
+/// Логгер.
+/// Асинхронная функция, возвращающая актуальный список доступных downstream-сервисов.
+public class QueryBasedLoadBalancer(ILogger logger, Func>> services)
+ : ILoadBalancer
+{
+ private const string IdQueryParamName = "id";
+
+ public string Type => nameof(QueryBasedLoadBalancer);
+
+ ///
+ /// Метод вызывается Ocelot после завершения запроса к downstream-сервису.
+ /// В текущей реализации ничего не делает (не требуется для query-based подхода).
+ ///
+ public void Release(ServiceHostAndPort hostAndPort) { }
+
+ ///
+ /// Основной метод выбора downstream-сервиса на основе query-параметра id текущего запроса.
+ ///
+ /// Контекст HTTP-запроса (используется для доступа к Query string).
+ ///
+ /// OkResponse с выбранным адресом сервиса в зависимости от query-параметра id, либо случайно выбранный адрес
+ /// сервиса, если query-параметр не задан.
+ ///
+ public async Task> LeaseAsync(HttpContext httpContext)
+ {
+ var currentServices = await services.Invoke();
+ var query = httpContext.Request.Query;
+
+ if (!query.TryGetValue(IdQueryParamName, out var idValues) || idValues.Count <= 0)
+ {
+ return SelectRandomService(currentServices);
+ }
+
+ var idStr = idValues.First();
+
+ if (string.IsNullOrWhiteSpace(idStr) || !int.TryParse(idStr, out var id) || id < 0)
+ {
+ return SelectRandomService(currentServices);
+ }
+
+ var index = id % currentServices.Count;
+ logger.LogInformation("Query based selected index={index}.", index);
+
+ return new OkResponse(currentServices[index].HostAndPort);
+ }
+
+ private OkResponse SelectRandomService(List currentServices)
+ {
+ var randomIndex = Random.Shared.Next(currentServices.Count);
+ logger.LogWarning("Query doesn't contain correct id parameter, index={randomIndex} selected by random.", randomIndex);
+
+ return new OkResponse(currentServices[randomIndex].HostAndPort);
+ }
+}
\ No newline at end of file
diff --git a/ResidentialBuilding.Gateway/Program.cs b/ResidentialBuilding.Gateway/Program.cs
new file mode 100644
index 0000000..3df6677
--- /dev/null
+++ b/ResidentialBuilding.Gateway/Program.cs
@@ -0,0 +1,35 @@
+using Ocelot.DependencyInjection;
+using Ocelot.Middleware;
+using ResidentialBuilding.Gateway.LoadBalancer;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.Services.AddCors(options =>
+{
+ options.AddPolicy("AllowLocalDev", policy =>
+ {
+ policy
+ .AllowAnyOrigin()
+ .WithHeaders("Content-Type")
+ .WithMethods("GET");
+ });
+});
+
+builder.Configuration
+ .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
+ .AddOcelot();
+
+builder.Services
+ .AddOcelot(builder.Configuration)
+ .AddCustomLoadBalancer((sp, _, discoveryProvider) =>
+ {
+ var logger = sp.GetRequiredService>();
+ return new QueryBasedLoadBalancer(logger, discoveryProvider.GetAsync);
+ });
+
+var app = builder.Build();
+
+app.UseCors("AllowLocalDev");
+await app.UseOcelot();
+
+await app.RunAsync();
diff --git a/ResidentialBuilding.Gateway/Properties/launchSettings.json b/ResidentialBuilding.Gateway/Properties/launchSettings.json
new file mode 100644
index 0000000..e210075
--- /dev/null
+++ b/ResidentialBuilding.Gateway/Properties/launchSettings.json
@@ -0,0 +1,38 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:22127",
+ "sslPort": 44310
+ }
+ },
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:5298",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:7014;http://localhost:5298",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/ResidentialBuilding.Gateway/ResidentialBuilding.Gateway.csproj b/ResidentialBuilding.Gateway/ResidentialBuilding.Gateway.csproj
new file mode 100644
index 0000000..8123f6c
--- /dev/null
+++ b/ResidentialBuilding.Gateway/ResidentialBuilding.Gateway.csproj
@@ -0,0 +1,17 @@
+
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
diff --git a/ResidentialBuilding.Gateway/appsettings.Development.json b/ResidentialBuilding.Gateway/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/ResidentialBuilding.Gateway/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/ResidentialBuilding.Gateway/appsettings.json b/ResidentialBuilding.Gateway/appsettings.json
new file mode 100644
index 0000000..10f68b8
--- /dev/null
+++ b/ResidentialBuilding.Gateway/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*"
+}
diff --git a/ResidentialBuilding.Gateway/ocelot.json b/ResidentialBuilding.Gateway/ocelot.json
new file mode 100644
index 0000000..54ac5e1
--- /dev/null
+++ b/ResidentialBuilding.Gateway/ocelot.json
@@ -0,0 +1,20 @@
+{
+ "Routes": [
+ {
+ "DownstreamPathTemplate": "/api/residential-building",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ { "Host": "localhost", "Port": 5201 },
+ { "Host": "localhost", "Port": 5202 },
+ { "Host": "localhost", "Port": 5203 },
+ { "Host": "localhost", "Port": 5204 },
+ { "Host": "localhost", "Port": 5205 }
+ ],
+ "UpstreamPathTemplate": "/residential-building",
+ "UpstreamHttpMethod": [ "GET" ],
+ "LoadBalancerOptions": {
+ "Type": "QueryBasedLoadBalancer"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/ResidentialBuilding.Generator/Controller/ResidentialBuildingController.cs b/ResidentialBuilding.Generator/Controller/ResidentialBuildingController.cs
new file mode 100644
index 0000000..0fbc4c2
--- /dev/null
+++ b/ResidentialBuilding.Generator/Controller/ResidentialBuildingController.cs
@@ -0,0 +1,37 @@
+using Generator.DTO;
+using Generator.Service;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Generator.Controller;
+
+///
+/// Контроллер для объектов жилого строительства.
+///
+[Route("api/residential-building")]
+[ApiController]
+public class ResidentialBuildingController(ILogger logger, IResidentialBuildingService residentialBuildingService) : ControllerBase
+{
+ ///
+ /// Получение объекта жилого строительства по id.
+ ///
+ /// Идентификатор объекта жилого строительства.
+ /// DTO объекта жилого строительства.
+ /// Успешное получение объекта.
+ /// Некорректный id.
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ public async Task> GetResidentialBuilding([FromQuery] int id)
+ {
+ if (id <= 0)
+ {
+ return BadRequest("id must be >= 0");
+ }
+
+ logger.LogInformation("Getting residential building with Id={id}.", id);
+ var result = await residentialBuildingService.GetByIdAsync(id);
+ logger.LogInformation("Residential building with Id={id} successfully received.", id);
+
+ return Ok(result);
+ }
+}
\ No newline at end of file
diff --git a/ResidentialBuilding.Generator/DTO/ResidentialBuildingDto.cs b/ResidentialBuilding.Generator/DTO/ResidentialBuildingDto.cs
new file mode 100644
index 0000000..2c9eac0
--- /dev/null
+++ b/ResidentialBuilding.Generator/DTO/ResidentialBuildingDto.cs
@@ -0,0 +1,57 @@
+namespace Generator.DTO;
+
+///
+/// DTO объекта жилого строительства
+///
+public class ResidentialBuildingDto
+{
+ ///
+ /// Идентификатор в системе
+ ///
+ public int Id { get; set; }
+
+ ///
+ /// Адрес
+ ///
+ public string Address { get; set; } = string.Empty;
+
+ ///
+ /// Тип недвижимости
+ ///
+ public string PropertyType { get; set; } = string.Empty;
+
+ ///
+ /// Год постройки
+ ///
+ public int BuildYear { get; set; }
+
+ ///
+ /// Общая площадь
+ ///
+ public double TotalArea { get; set; }
+
+ ///
+ /// Жилая площадь
+ ///
+ public double LivingArea { get; set; }
+
+ ///
+ /// Этаж
+ ///
+ public int? Floor { get; set; }
+
+ ///
+ /// Этажность
+ ///
+ public int TotalFloors { get; set; }
+
+ ///
+ /// Кадастровый номер
+ ///
+ public string CadastralNumber { get; set; } = string.Empty;
+
+ ///
+ /// Кадастровая стоимость
+ ///
+ public decimal CadastralValue { get; set; }
+}
\ No newline at end of file
diff --git a/ResidentialBuilding.Generator/Generator/ResidentialBuildingGenerator.cs b/ResidentialBuilding.Generator/Generator/ResidentialBuildingGenerator.cs
new file mode 100644
index 0000000..0468a35
--- /dev/null
+++ b/ResidentialBuilding.Generator/Generator/ResidentialBuildingGenerator.cs
@@ -0,0 +1,100 @@
+using Bogus;
+using Generator.DTO;
+
+namespace Generator.Generator;
+
+///
+/// Генератор объектов жилого строительства на основе Bogus
+///
+public class ResidentialBuildingGenerator(ILogger logger)
+{
+ private const int MinBuildYear = 1900;
+
+ private const double MinTotalArea = 10.0;
+
+ private const double MaxTotalArea = 1000.0;
+
+ private const double MinLivingAreaPartOfTotalArea = 0.5;
+
+ private const double MaxLivingAreaPartOfTotalArea = 0.85;
+
+ private const int MinTotalFloors = 1;
+
+ private const int MaxTotalFloors = 100;
+
+ private const double MinPricePerM2 = 35;
+
+ private const double MaxPricePerM2 = 200;
+
+ private static readonly string[] _propertyTypes =
+ [
+ "Квартира",
+ "ИЖС",
+ "Апартаменты",
+ "Офис"
+ ];
+
+ private static readonly Faker _faker = new Faker("ru")
+ .RuleFor(x => x.Address, f => f.Address.FullAddress())
+ .RuleFor(x => x.PropertyType, f => f.PickRandom(_propertyTypes))
+ .RuleFor(x => x.BuildYear, f => f.Random.Int(MinBuildYear, DateTime.Today.Year))
+ .RuleFor(x => x.TotalArea, f => Math.Round(f.Random.Double(MinTotalArea, MaxTotalArea), 2))
+ .RuleFor(x => x.LivingArea, (f, dto) =>
+ {
+ var livingAreaPartOfTotalArea =
+ f.Random.Double(MinLivingAreaPartOfTotalArea, MaxLivingAreaPartOfTotalArea);
+ return Math.Round(livingAreaPartOfTotalArea * dto.TotalArea, 2);
+ })
+ .RuleFor(x => x.TotalFloors, f => f.Random.Int(MinTotalFloors, MaxTotalFloors))
+ .RuleFor(x => x.Floor, (f, dto) =>
+ {
+ if (dto.PropertyType is "ИЖС")
+ {
+ return null;
+ }
+
+ return f.Random.Int(1, dto.TotalFloors);
+ })
+ .RuleFor(x => x.CadastralNumber, f =>
+ $"{f.Random.Int(1, 99):D2}:" +
+ $"{f.Random.Int(1, 99):D2}:" +
+ $"{f.Random.Int(1, 9999999):D7}:" +
+ $"{f.Random.Int(1, 9999):D4}")
+ .RuleFor(x => x.CadastralValue, (f, dto) =>
+ {
+ var pricePerM2 = f.Random.Double(MinPricePerM2, MaxPricePerM2);
+ var price = dto.TotalArea * pricePerM2;
+ return (decimal)Math.Round(price, 2);
+ });
+
+ ///
+ /// Генерирует объект жилого строительства для заданного идентификатора
+ ///
+ /// Идентификатор объекта жилого строительства
+ /// Сгенерированный объект жилого строительства
+ public ResidentialBuildingDto Generate(int id)
+ {
+ logger.LogInformation("Generating Residential Building for Id={id}", id);
+
+ var generatedObject = _faker.Generate();
+ generatedObject.Id = id;
+
+ logger.LogInformation(
+ "Residential building generated: {@Building}",
+ new
+ {
+ generatedObject.Id,
+ generatedObject.Address,
+ generatedObject.PropertyType,
+ generatedObject.BuildYear,
+ generatedObject.TotalArea,
+ generatedObject.LivingArea,
+ generatedObject.Floor,
+ generatedObject.TotalFloors,
+ generatedObject.CadastralNumber,
+ generatedObject.CadastralValue
+ });
+
+ return generatedObject;
+ }
+}
\ No newline at end of file
diff --git a/ResidentialBuilding.Generator/Program.cs b/ResidentialBuilding.Generator/Program.cs
new file mode 100644
index 0000000..a3e90dc
--- /dev/null
+++ b/ResidentialBuilding.Generator/Program.cs
@@ -0,0 +1,19 @@
+using Generator.Generator;
+using Generator.Service;
+using ResidentialBuilding.ServiceDefaults;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.AddServiceDefaults();
+builder.AddRedisDistributedCache("residential-building-cache");
+
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+
+builder.Services.AddControllers();
+
+var app = builder.Build();
+
+app.MapControllers();
+
+app.Run();
\ No newline at end of file
diff --git a/ResidentialBuilding.Generator/Properties/launchSettings.json b/ResidentialBuilding.Generator/Properties/launchSettings.json
new file mode 100644
index 0000000..a340fa1
--- /dev/null
+++ b/ResidentialBuilding.Generator/Properties/launchSettings.json
@@ -0,0 +1,38 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:39434",
+ "sslPort": 44329
+ }
+ },
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:5200",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:7291;http://localhost:5200",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/ResidentialBuilding.Generator/ResidentialBuilding.Generator.csproj b/ResidentialBuilding.Generator/ResidentialBuilding.Generator.csproj
new file mode 100644
index 0000000..07dcd97
--- /dev/null
+++ b/ResidentialBuilding.Generator/ResidentialBuilding.Generator.csproj
@@ -0,0 +1,20 @@
+
+
+
+ net8.0
+ enable
+ enable
+ Generator
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/ResidentialBuilding.Generator/Service/IResidentialBuildingService.cs b/ResidentialBuilding.Generator/Service/IResidentialBuildingService.cs
new file mode 100644
index 0000000..0247670
--- /dev/null
+++ b/ResidentialBuilding.Generator/Service/IResidentialBuildingService.cs
@@ -0,0 +1,21 @@
+using Generator.DTO;
+
+namespace Generator.Service;
+
+///
+/// Сервис получения объектов жилого строительства по идентификатору.
+/// Если удалось найти объект в кэше - возвращает его, иначе генерирует, кэширует и возвращает сгенерированный.
+///
+public interface IResidentialBuildingService
+{
+ ///
+ /// Пытается найти в кэше объект с заданным идентификатором:
+ /// если удалось, то десериализует объект из JSON-а и возвращает;
+ /// если не удалось или произошла ошибка в ходе получения/десериализации, то генерирует объект, сохраняет в кэш и
+ /// возвращает сгенерированный.
+ ///
+ /// Идентификатор объекта жилого строительства.
+ /// Токен отмены.
+ /// DTO объекта жилого строительства.
+ public Task GetByIdAsync(int id, CancellationToken cancellationToken = default);
+}
\ No newline at end of file
diff --git a/ResidentialBuilding.Generator/Service/ResidentialBuildingService.cs b/ResidentialBuilding.Generator/Service/ResidentialBuildingService.cs
new file mode 100644
index 0000000..974b172
--- /dev/null
+++ b/ResidentialBuilding.Generator/Service/ResidentialBuildingService.cs
@@ -0,0 +1,79 @@
+using Generator.DTO;
+using Generator.Generator;
+using Microsoft.Extensions.Caching.Distributed;
+using System.Text.Json;
+
+namespace Generator.Service;
+
+public class ResidentialBuildingService(
+ ILogger logger,
+ ResidentialBuildingGenerator generator,
+ IDistributedCache cache,
+ IConfiguration configuration
+ ) : IResidentialBuildingService
+{
+ private const string CacheKeyPrefix = "residential-building:";
+
+ private const int CacheExpirationTimeMinutesDefault = 15;
+
+ private readonly TimeSpan _cacheExpirationTimeMinutes = TimeSpan.FromMinutes(configuration.GetValue("CacheSettings:ExpirationTimeMinutes", CacheExpirationTimeMinutesDefault));
+
+ public async Task GetByIdAsync(int id, CancellationToken cancellationToken = default)
+ {
+ var cacheKey = $"{CacheKeyPrefix}{id}";
+
+ string? jsonCached = null;
+ try
+ {
+ jsonCached = await cache.GetStringAsync(cacheKey, cancellationToken);
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(ex, "Failed to read from distributed cache for key={cacheKey}. Falling back to generation.", cacheKey);
+ }
+
+ if (!string.IsNullOrEmpty(jsonCached))
+ {
+ logger.LogInformation("Cache for residential building with Id={} received.", id);
+
+ ResidentialBuildingDto? objCached = null;
+ try
+ {
+ objCached = JsonSerializer.Deserialize(jsonCached);
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(ex, "Invalid JSON in residential building cache for key {cacheKey}.", cacheKey);
+ }
+
+ if (objCached is null)
+ {
+ logger.LogWarning("Cache for residential building with Id={id} returned null.", id);
+ }
+ else
+ {
+ logger.LogInformation("Cache for residential building with Id={id} is valid, returned", id);
+ return objCached;
+ }
+ }
+
+ var obj = generator.Generate(id);
+
+ try
+ {
+ var cacheOptions = new DistributedCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = _cacheExpirationTimeMinutes
+ };
+ await cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(obj), cacheOptions, cancellationToken);
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(ex, "Failed to write residential building with Id={id} to cache. Still returning generated value.", id);
+ }
+
+ logger.LogInformation("Generated and cached residential building with Id={id}", id);
+
+ return obj;
+ }
+}
\ No newline at end of file
diff --git a/ResidentialBuilding.Generator/appsettings.Development.json b/ResidentialBuilding.Generator/appsettings.Development.json
new file mode 100644
index 0000000..af36b86
--- /dev/null
+++ b/ResidentialBuilding.Generator/appsettings.Development.json
@@ -0,0 +1,11 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "CacheSettings": {
+ "ExpirationTimeMinutes": 5
+ }
+}
diff --git a/ResidentialBuilding.Generator/appsettings.json b/ResidentialBuilding.Generator/appsettings.json
new file mode 100644
index 0000000..10f68b8
--- /dev/null
+++ b/ResidentialBuilding.Generator/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*"
+}
diff --git a/ResidentialBuilding.ServiceDefaults/Extensions.cs b/ResidentialBuilding.ServiceDefaults/Extensions.cs
new file mode 100644
index 0000000..5e59484
--- /dev/null
+++ b/ResidentialBuilding.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.Hosting;
+using Microsoft.Extensions.Logging;
+using OpenTelemetry;
+using OpenTelemetry.Metrics;
+using OpenTelemetry.Trace;
+
+namespace ResidentialBuilding.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/ResidentialBuilding.ServiceDefaults/ResidentialBuilding.ServiceDefaults.csproj b/ResidentialBuilding.ServiceDefaults/ResidentialBuilding.ServiceDefaults.csproj
new file mode 100644
index 0000000..9fb1f65
--- /dev/null
+++ b/ResidentialBuilding.ServiceDefaults/ResidentialBuilding.ServiceDefaults.csproj
@@ -0,0 +1,22 @@
+
+
+
+ net8.0
+ enable
+ enable
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+