Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Api.Gateway/Api.Gateway.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Ocelot" Version="24.1.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\CreditApp\CreditApp.ServiceDefaults\CreditApp.ServiceDefaults.csproj" />
</ItemGroup>

</Project>
34 changes: 34 additions & 0 deletions Api.Gateway/LoadBalancing/QueryBasedLoadBalancer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Ocelot.LoadBalancer.Interfaces;
using Ocelot.Responses;
using Ocelot.Values;

namespace Api.Gateway.LoadBalancing;

/// <summary>
/// Балансировщик нагрузки на основе параметра запроса.
/// Реплика определяется как остаток от деления id на число реплик: index = id % N.
/// </summary>
public class QueryBasedLoadBalancer(Func<Task<List<Service>>> services) : ILoadBalancer
{
public string Type => nameof(QueryBasedLoadBalancer);

public async Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext httpContext)
{
var list = await services();

if (list.Count == 0)
throw new InvalidOperationException("No available downstream services.");

var query = httpContext.Request.Query;

if (!query.ContainsKey("id") || !int.TryParse(query["id"], out var id))
{
return new OkResponse<ServiceHostAndPort>(list[0].HostAndPort);
}

var index = Math.Abs(id) % list.Count;
return new OkResponse<ServiceHostAndPort>(list[index].HostAndPort);
}

public void Release(ServiceHostAndPort hostAndPort) { }
}
38 changes: 38 additions & 0 deletions Api.Gateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Api.Gateway.LoadBalancing;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
builder.Services.AddServiceDiscovery();
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);

var overrides = new Dictionary<string, string?>();
for (var i = 0; Environment.GetEnvironmentVariable($"services__credit-app-{i}__https__0") is { } url; i++)
{
var uri = new Uri(url);
overrides[$"Routes:0:DownstreamHostAndPorts:{i}:Host"] = uri.Host;
overrides[$"Routes:0:DownstreamHostAndPorts:{i}:Port"] = uri.Port.ToString();
}

if (overrides.Count > 0)
builder.Configuration.AddInMemoryCollection(overrides);

builder.Services.AddOcelot()
.AddCustomLoadBalancer<QueryBasedLoadBalancer>((_, _, discoveryProvider) => new(discoveryProvider.GetAsync));

var allowedOrigins = builder.Configuration.GetSection("CorsSettings:AllowedOrigins").Get<string[]>() ?? [];
builder.Services.AddCors(options => options.AddPolicy("AllowClient", policy =>
policy.WithOrigins(allowedOrigins)
.AllowAnyMethod()
.AllowAnyHeader()));

var app = builder.Build();

app.UseCors("AllowClient");
app.MapDefaultEndpoints();

await app.UseOcelot();

app.Run();
38 changes: 38 additions & 0 deletions Api.Gateway/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:63809",
"sslPort": 44394
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5087",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7265;http://localhost:5087",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
8 changes: 8 additions & 0 deletions Api.Gateway/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
15 changes: 15 additions & 0 deletions Api.Gateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"CorsSettings": {
"AllowedOrigins": [
"http://localhost:5127",
"https://localhost:7282"
]
}
}
18 changes: 18 additions & 0 deletions Api.Gateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/credit-application",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/api/credit-application",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 8000 },
{ "Host": "localhost", "Port": 8001 },
{ "Host": "localhost", "Port": 8002 }
],
"LoadBalancerOptions": {
"Type": "QueryBasedLoadBalancer"
}
}
]
}
8 changes: 4 additions & 4 deletions Client.Wasm/Components/StudentCard.razor
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
</CardHeader>
<CardBody>
<UnorderedList Unstyled>
<UnorderedListItem>Номер <Strong>№X "Название лабораторной"</Strong></UnorderedListItem>
<UnorderedListItem>Вариант <Strong>№Х "Название варианта"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Фамилией Именем 65ХХ</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://puginarug.com/">Ссылка на форк</Link></UnorderedListItem>
<UnorderedListItem>Номер <Strong>№2 "Балансировка нагрузки"</Strong></UnorderedListItem>
<UnorderedListItem>Вариант <Strong>№11 "Балансировка нагрузки"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнил <Strong>Маясов Данила Вячеславович 6511</Strong></UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/danyala1/cloud-development">Ссылка на форк</Link></UnorderedListItem>
</UnorderedList>
</CardBody>
</Card>
6 changes: 3 additions & 3 deletions Client.Wasm/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "http://localhost:5127",
"environmentVariables": {
Expand All @@ -22,7 +22,7 @@
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "https://localhost:7282;http://localhost:5127",
"environmentVariables": {
Expand All @@ -31,7 +31,7 @@
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
Expand Down
2 changes: 1 addition & 1 deletion Client.Wasm/wwwroot/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
"BaseAddress": ""
"BaseAddress": "https://localhost:7265/credit-application"
}
24 changes: 24 additions & 0 deletions CloudDevelopment.sln
Original file line number Diff line number Diff line change
Expand Up @@ -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}") = "CreditApp.AppHost", "CreditApp\CreditApp.AppHost\CreditApp.AppHost.csproj", "{39378C50-BF1E-4D2E-B306-22BCBB212135}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.ServiceDefaults", "CreditApp\CreditApp.ServiceDefaults\CreditApp.ServiceDefaults.csproj", "{A7B14B5D-B738-B77E-404F-CF5182E30A41}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.Api", "CreditApp.Api\CreditApp.Api.csproj", "{E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -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
{39378C50-BF1E-4D2E-B306-22BCBB212135}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{39378C50-BF1E-4D2E-B306-22BCBB212135}.Debug|Any CPU.Build.0 = Debug|Any CPU
{39378C50-BF1E-4D2E-B306-22BCBB212135}.Release|Any CPU.ActiveCfg = Release|Any CPU
{39378C50-BF1E-4D2E-B306-22BCBB212135}.Release|Any CPU.Build.0 = Release|Any CPU
{A7B14B5D-B738-B77E-404F-CF5182E30A41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A7B14B5D-B738-B77E-404F-CF5182E30A41}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A7B14B5D-B738-B77E-404F-CF5182E30A41}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A7B14B5D-B738-B77E-404F-CF5182E30A41}.Release|Any CPU.Build.0 = Release|Any CPU
{E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Release|Any CPU.Build.0 = Release|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
23 changes: 23 additions & 0 deletions CreditApp.Api/CreditApp.Api.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="9.5.2" />
<PackageReference Include="Bogus" Version="35.6.5" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\CreditApp\CreditApp.ServiceDefaults\CreditApp.ServiceDefaults.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="Models\" />
<Folder Include="Services\" />
</ItemGroup>

</Project>
57 changes: 57 additions & 0 deletions CreditApp.Api/Models/CreditApplication.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
namespace CreditApp.Api.Models;

/// <summary>
/// Кредитная заявка
/// </summary>
public class CreditApplication
{
/// <summary>
/// Идентификатор в системе
/// </summary>
public int Id { get; set; }

/// <summary>
/// Тип кредита (например, "Потребительский", "Ипотека", "Автокредит")
/// </summary>
public required string LoanType { get; set; }

/// <summary>
/// Запрашиваемая сумма, округлённая до двух знаков после запятой
/// </summary>
public decimal RequestedAmount { get; set; }

/// <summary>
/// Срок кредита в месяцах
/// </summary>
public int TermMonths { get; set; }

/// <summary>
/// Процентная ставка (не менее ставки ЦБ РФ), округлённая до двух знаков после запятой
/// </summary>
public double InterestRate { get; set; }

/// <summary>
/// Дата подачи заявки (не более двух лет назад от текущей даты)
/// </summary>
public DateOnly ApplicationDate { get; set; }

/// <summary>
/// Необходимость страховки
/// </summary>
public bool InsuranceRequired { get; set; }

/// <summary>
/// Статус заявки (например, "Новая", "В обработке", "Одобрена", "Отклонена")
/// </summary>
public required string Status { get; set; }

/// <summary>
/// Дата решения. Заполняется только для терминальных статусов ("Одобрена", "Отклонена")
/// </summary>
public DateOnly? DecisionDate { get; set; }

/// <summary>
/// Одобренная сумма. Заполняется только при статусе "Одобрена", не превышает <see cref="RequestedAmount"/>
/// </summary>
public decimal? ApprovedAmount { get; set; }
}
18 changes: 18 additions & 0 deletions CreditApp.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using CreditApp.Api.Services;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
builder.AddRedisDistributedCache("redis");

builder.Services.AddSingleton<CreditApplicationGenerator>();
builder.Services.AddScoped<ICreditApplicationService, CreditApplicationService>();

var app = builder.Build();

app.MapDefaultEndpoints();

app.MapGet("/api/credit-application", async (int id, ICreditApplicationService service) =>
await service.GetOrGenerate(id));

app.Run();
Loading