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="..\Patient.ServiceDefaults\Patient.ServiceDefaults.csproj" />
</ItemGroup>

</Project>
35 changes: 35 additions & 0 deletions Api.Gateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Api.Gateway;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Patient.ServiceDefaults;

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot()
.AddCustomLoadBalancer((sp, _, provider) =>
new WeightedRoundRobin(provider.GetAsync, sp.GetRequiredService<IConfiguration>()));

var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];

builder.Services.AddCors(options =>
{
options.AddPolicy("AllowLocalDev", policy =>
{
policy
.WithOrigins(allowedOrigins)
.WithHeaders("Content-Type")
.WithMethods("GET");
});
});

builder.AddServiceDefaults();
var app = builder.Build();

app.UseCors("AllowLocalDev");

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:15501",
"sslPort": 44374
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5009",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7212;http://localhost:5009",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
59 changes: 59 additions & 0 deletions Api.Gateway/WeightedRoundRobin.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using Ocelot.LoadBalancer.Interfaces;
using Ocelot.Responses;
using Ocelot.Values;

namespace Api.Gateway;

/// <summary>
/// Балансировщик Weighted Round Robin: распределяет запросы циклически
/// с учётом весов реплик из секции <c>WeightedRoundRobin:Weights</c>.
/// </summary>
/// <param name="serviceProviderFactory">Делегат, возвращающий список реплик.</param>
/// <param name="configuration">Источник весов.</param>
public class WeightedRoundRobin(Func<Task<List<Service>>> serviceProviderFactory, IConfiguration configuration) : ILoadBalancer
{
private readonly int[] _weights = configuration.GetSection("WeightedRoundRobin:Weights").Get<int[]>() ?? [];
private long _counter = -1;

public string Type => nameof(WeightedRoundRobin);

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

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

var serviceIndex = SelectIndex(services.Count);

return new OkResponse<ServiceHostAndPort>(services[serviceIndex].HostAndPort);
}

public void Release(ServiceHostAndPort hostAndPort) { }

private int SelectIndex(int serviceCount)
{
var totalWeight = 0L;
for (var i = 0; i < serviceCount; i++)
totalWeight += GetWeight(i);

var ticket = (Interlocked.Increment(ref _counter) & long.MaxValue) % totalWeight;

var cumulative = 0L;
for (var i = 0; i < serviceCount; i++)
{
cumulative += GetWeight(i);
if (ticket < cumulative)
return i;
}

return serviceCount - 1;
}

private int GetWeight(int index)
{
if (index >= _weights.Length) return 1;
var weight = _weights[index];
return weight > 0 ? weight : 1;
}
}
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"
}
}
}
18 changes: 18 additions & 0 deletions Api.Gateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Cors": {
"AllowedOrigins": [
"http://localhost:5127",
"https://localhost:7282"
]
},
"WeightedRoundRobin": {
"Weights": [ 5, 4, 3, 2, 1 ]
}
}
20 changes: 20 additions & 0 deletions Api.Gateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/api/patient",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/api/patient",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 5200 },
{ "Host": "localhost", "Port": 5201 },
{ "Host": "localhost", "Port": 5202 },
{ "Host": "localhost", "Port": 5203 },
{ "Host": "localhost", "Port": 5204 }
],
"LoadBalancerOptions": {
"Type": "WeightedRoundRobin"
}
}
]
}
87 changes: 75 additions & 12 deletions Client.Wasm/Components/DataCard.razor
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
@inject IConfiguration Configuration
@inject Microsoft.Extensions.Configuration.IConfiguration Configuration
@inject HttpClient Client

<CardDeck>
<Card>
<CardHeader>
<Heading Size="HeadingSize.Is5"><Icon Name="IconName.Table" /> Характеристики текущего объекта</Heading>
<Heading Size="HeadingSize.Is5"><Icon Name="IconName.Table" /> Характеристики пациента</Heading>
</CardHeader>
<CardBody>
<Table Bordered >
Expand All @@ -16,7 +16,7 @@
</TableRow>
</TableHeader>
<TableBody>
@if(Value is null)
@if (Value is null)
{
<TableRow>
<TableRowCell>1</TableRowCell>
Expand All @@ -26,13 +26,13 @@
}
else
{
var array = Value.ToArray();
foreach (var property in array)
var rows = BuildRows();
foreach (var row in rows)
{
<TableRow>
<TableRowCell>@(Array.IndexOf(array, property)+1)</TableRowCell>
<TableRowCell>@property.Key</TableRowCell>
<TableRowCell>@property.Value?.ToString()</TableRowCell>
<TableRowCell>@row.Number</TableRowCell>
<TableRowCell>@row.Name</TableRowCell>
<TableRowCell>@row.Value</TableRowCell>
</TableRow>
}
}
Expand All @@ -43,32 +43,95 @@

<Card Margin="Margin.Is3.OnY">
<CardHeader>
<Heading Size="HeadingSize.Is5"><Icon Name="IconName.Send" /> Запросить новый объект</Heading>
<Heading Size="HeadingSize.Is5"><Icon Name="IconName.Send" /> Запросить нового пациента</Heading>
</CardHeader>
<CardBody>
<Row>
<Column ColumnSize="ColumnSize.Is4">
<Text>Идентификатор нового объекта:</Text>
<Text>Идентификатор пациента:</Text>
</Column>
<Column ColumnSize="ColumnSize.Is4">
<NumericEdit TValue="int" @bind-Value="@Id"/>
</Column>
<Column ColumnSize="ColumnSize.Is4">
<Button Clicked=RequestNewData Color="Color.Primary">Запросить данные <Icon Name="IconName.ArrowRight" /></Button>
<Button Clicked=RequestNewData Color="Color.Primary">Запросить данные <Icon Name="IconName.ArrowRight" /></Button>
</Column>
</Row>
</CardBody>
</Card>
</CardDeck>

@code {
private static readonly string[] PropertyOrder =
[
"id",
"fullName",
"address",
"birthDate",
"height",
"weight",
"bloodGroup",
"rhFactor",
"lastExaminationDate",
"isVaccinated"
];

private static readonly Dictionary<string, string> PropertyNames = new()
{
["id"] = "Идентификатор в системе",
["fullName"] = "ФИО пациента",
["address"] = "Адрес проживания",
["birthDate"] = "Дата рождения",
["height"] = "Рост",
["weight"] = "Вес",
["bloodGroup"] = "Группа крови",
["rhFactor"] = "Резус-фактор",
["lastExaminationDate"] = "Дата последнего осмотра",
["isVaccinated"] = "Отметка о вакцинации"
};

private JsonObject? Value { get; set; }
private int Id { get; set; }

private async Task RequestNewData()
{
var baseAddress = Configuration["BaseAddress"] ?? throw new KeyNotFoundException("Конфигурация клиента не содержит параметра BaseAddress");
Value = await Client.GetFromJsonAsync<JsonObject>($"{baseAddress}?id={Id}", new JsonSerializerOptions { });
var requestUri = string.Concat(baseAddress, "?id=", Id);
Value = await Client.GetFromJsonAsync<JsonObject>(requestUri, new JsonSerializerOptions());
StateHasChanged();
}

private IReadOnlyList<(int Number, string Name, string Value)> BuildRows()
{
if (Value is null)
{
return [];
}

return PropertyOrder
.Select((propertyKey, i) => (
i + 1,
PropertyNames.GetValueOrDefault(propertyKey, propertyKey),
FormatValue(propertyKey, Value[propertyKey])))
.ToList();
}

private static string FormatValue(string propertyKey, JsonNode? node)
{
if (node is null)
{
return "нет данных";
}

var rawValue = node.ToString();

return propertyKey switch
{
"height" => $"{rawValue} см",
"weight" => $"{rawValue} кг",
"rhFactor" => rawValue.Equals("true", StringComparison.OrdinalIgnoreCase) ? "положительный" : "отрицательный",
"isVaccinated" => rawValue.Equals("true", StringComparison.OrdinalIgnoreCase) ? "да" : "нет",
_ => rawValue
};
}
}
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>№20 "Медицинский пациент"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнила <Strong>Горбунцова Александра 6512</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/litirnntir/cloud-development/tree/main">Ссылка на форк</Link></UnorderedListItem>
</UnorderedList>
</CardBody>
</Card>
2 changes: 1 addition & 1 deletion Client.Wasm/Pages/Home.razor
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
@page "/"

<DataCard/>
<DataCard/>
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
Loading
Loading