Skip to content
Open
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>№3 "Интеграционное тестирование"</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"
}
36 changes: 36 additions & 0 deletions CloudDevelopment.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ 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
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.AppHost.Tests", "CreditApp.AppHost.Tests\CreditApp.AppHost.Tests.csproj", "{F1E58572-4194-45C8-BAC1-CE4638047D36}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Service.FileStorage", "Service.FileStorage\Service.FileStorage.csproj", "{395BE70D-7DB4-7F62-3FF9-C8EE68E5C610}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -15,6 +27,30 @@ 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
{F1E58572-4194-45C8-BAC1-CE4638047D36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F1E58572-4194-45C8-BAC1-CE4638047D36}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F1E58572-4194-45C8-BAC1-CE4638047D36}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F1E58572-4194-45C8-BAC1-CE4638047D36}.Release|Any CPU.Build.0 = Release|Any CPU
{395BE70D-7DB4-7F62-3FF9-C8EE68E5C610}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{395BE70D-7DB4-7F62-3FF9-C8EE68E5C610}.Debug|Any CPU.Build.0 = Debug|Any CPU
{395BE70D-7DB4-7F62-3FF9-C8EE68E5C610}.Release|Any CPU.ActiveCfg = Release|Any CPU
{395BE70D-7DB4-7F62-3FF9-C8EE68E5C610}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
21 changes: 21 additions & 0 deletions CreditApp.Api/CreditApp.Api.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<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" />
<PackageReference Include="AWSSDK.SimpleNotificationService" Version="4.0.2.17" />
<PackageReference Include="LocalStack.Client" Version="2.0.0" />
<PackageReference Include="LocalStack.Client.Extensions" Version="2.0.0" />
</ItemGroup>

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

</Project>
15 changes: 15 additions & 0 deletions CreditApp.Api/Messaging/IProducerService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using CreditApp.Api.Models;

namespace CreditApp.Api.Messaging;

/// <summary>
/// Интерфейс службы для отправки кредитных заявок в брокер сообщений
/// </summary>
public interface IProducerService
{
/// <summary>
/// Отправляет сообщение с кредитной заявкой в брокер
/// </summary>
/// <param name="application">Кредитная заявка</param>
public Task SendMessage(CreditApplication application);
}
48 changes: 48 additions & 0 deletions CreditApp.Api/Messaging/SnsPublisherService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
using CreditApp.Api.Models;
using System.Net;
using System.Text.Json;

namespace CreditApp.Api.Messaging;

/// <summary>
/// Служба для отправки сообщений в SNS
/// </summary>
/// <param name="client">Клиент SNS</param>
/// <param name="configuration">Конфигурация</param>
/// <param name="logger">Логгер</param>
public class SnsPublisherService(
IAmazonSimpleNotificationService client,
IConfiguration configuration,
ILogger<SnsPublisherService> logger) : IProducerService
{
/// <summary>
/// Уникальный идентификатор топика SNS
/// </summary>
private readonly string _topicArn = configuration["AWS:Resources:SNSTopicArn"]
?? throw new KeyNotFoundException("SNS topic ARN was not found in configuration");

/// <inheritdoc/>
public async Task SendMessage(CreditApplication application)
{
try
{
var json = JsonSerializer.Serialize(application);
var request = new PublishRequest
{
Message = json,
TopicArn = _topicArn
};
var response = await client.PublishAsync(request);
if (response.HttpStatusCode == HttpStatusCode.OK)
logger.LogInformation("Credit application {Id} sent to SNS", application.Id);
else
throw new Exception($"SNS returned {response.HttpStatusCode}");
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to send credit application {Id} through SNS", application.Id);
}
}
}
Loading