-
Notifications
You must be signed in to change notification settings - Fork 33
Елагин Денис 6513 Лаб. 2 #24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Donistr
wants to merge
24
commits into
itsecd:main
Choose a base branch
from
Donistr:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+856
−5
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
0a769f7
feat: добавил ServiceDefaults
Donistr 69e6dba
feat: добавил сервис Generator
Donistr 9b66e86
fix: добавил файлы, которые забыл закоммитить
Donistr 4eaaee0
feat: добавил AppHost
Donistr 52dc141
fix: поправил в клиенте карточку студента и сделал чтобы url получени…
Donistr 70c225b
style: запустил code cleanup во всём проекте
Donistr ae35609
refactor: вынес faker в private static readonly поле
Donistr 8724252
style: сделал revert коммита с клинапом
Donistr 6cab0cf
fix: убрал serilog, чтобы пофиксить структурное логирование
Donistr c6f84a5
refactor: убрал метод CreateCahcheOptions
Donistr 4c1f771
refactor: улучшил логирование сгенерированного объекта ResidentialBui…
Donistr 51fac4e
fix: поправил cors
Donistr 38f2929
refactor: убрал объявление бесполезной переменной generator
Donistr fbc4abf
reafactor: исправил порядок импортов
Donistr 7712171
refactor: добавил в контроллер атрибуты с возвращаемыми типами
Donistr 9d30440
fix: изменил клиент под gateway и под 2 лабу
Donistr 3369278
fix: изменил генератор под query параметр
Donistr ad90a89
feat: добавил ocelot с кастомным quary based балансировщиком нагрузки
Donistr b900ae7
fix: изменил AppHost под ocelot
Donistr 4208170
fix: убрал бесполезный lock из балансировщика
Donistr 3191a83
refactor: сделал в AppHost.cs создание генераторов через цикл
Donistr 1c6352f
refactor: убрал бесполезный cors у сервиса-генератора
Donistr 8f9d89b
refactor: убрал из конфига оцелота плейсхолдеры из маршрутов
Donistr 472fee8
fix: исправил балансировщик, чтобы он соответствовал заданию
Donistr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,5 +6,5 @@ | |
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "BaseAddress": "" | ||
| "BaseAddress": "http://localhost:5300/residential-building" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| var builder = DistributedApplication.CreateBuilder(args); | ||
|
|
||
| var cache = builder.AddRedis("residential-building-cache") | ||
| .WithRedisInsight(containerName: "residential-building-insight"); | ||
|
|
||
| var gateway = builder.AddProject<Projects.ResidentialBuilding_Gateway>("gateway") | ||
| .WithEndpoint("http", endpoint => endpoint.Port = 5300) | ||
| .WithExternalHttpEndpoints(); | ||
|
|
||
| const int generatorPortBase = 5200; | ||
| for (var i = 1; i <= 5; ++i) | ||
| { | ||
| var i1 = i; | ||
| var generator = builder.AddProject<Projects.ResidentialBuilding_Generator>($"generator-{i}") | ||
| .WithReference(cache, "residential-building-cache") | ||
| .WithEndpoint("http", endpoint => endpoint.Port = generatorPortBase + i1) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. У тебя и с |
||
| .WaitFor(cache); | ||
|
|
||
| gateway.WaitFor(generator); | ||
| } | ||
|
|
||
| builder.AddProject<Projects.Client_Wasm>("client") | ||
| .WithReference(gateway) | ||
| .WaitFor(gateway); | ||
|
|
||
| builder.Build().Run(); | ||
29 changes: 29 additions & 0 deletions
29
ResidentialBuilding.AppHost/Properties/launchSettings.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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" | ||
| } | ||
| } | ||
| } | ||
| } |
24 changes: 24 additions & 0 deletions
24
ResidentialBuilding.AppHost/ResidentialBuilding.AppHost.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <Sdk Name="Aspire.AppHost.Sdk" Version="9.5.0" /> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| <UserSecretsId>ed7e1e47-dc98-4419-8424-85412466aa9b</UserSecretsId> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.Hosting.AppHost" Version="9.5.0" /> | ||
| <PackageReference Include="Aspire.Hosting.Redis" Version="9.5.0" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\ResidentialBuilding.Generator\ResidentialBuilding.Generator.csproj" /> | ||
| <ProjectReference Include="..\Client.Wasm\Client.Wasm.csproj" /> | ||
| <ProjectReference Include="..\ResidentialBuilding.Gateway\ResidentialBuilding.Gateway.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning", | ||
| "Aspire.Hosting.Dcp": "Warning" | ||
| } | ||
| } | ||
| } |
64 changes: 64 additions & 0 deletions
64
ResidentialBuilding.Gateway/LoadBalancer/QueryBasedLoadBalancer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| using Ocelot.LoadBalancer.Interfaces; | ||
| using Ocelot.Responses; | ||
| using Ocelot.Values; | ||
|
|
||
| namespace ResidentialBuilding.Gateway.LoadBalancer; | ||
|
|
||
| /// <summary> | ||
| /// Query-based балансировщик нагрузки для Ocelot. | ||
| /// Выбирает downstream-сервис на основе query-параметра id запроса. | ||
| /// </summary> | ||
| /// <param name="logger">Логгер.</param> | ||
| /// <param name="services">Асинхронная функция, возвращающая актуальный список доступных downstream-сервисов.</param> | ||
| public class QueryBasedLoadBalancer(ILogger<QueryBasedLoadBalancer> logger, Func<Task<List<Service>>> services) | ||
| : ILoadBalancer | ||
| { | ||
| private const string IdQueryParamName = "id"; | ||
|
|
||
| public string Type => nameof(QueryBasedLoadBalancer); | ||
|
|
||
| /// <summary> | ||
| /// Метод вызывается Ocelot после завершения запроса к downstream-сервису. | ||
| /// В текущей реализации ничего не делает (не требуется для query-based подхода). | ||
| /// </summary> | ||
| public void Release(ServiceHostAndPort hostAndPort) { } | ||
|
|
||
| /// <summary> | ||
| /// Основной метод выбора downstream-сервиса на основе query-параметра id текущего запроса. | ||
| /// </summary> | ||
| /// <param name="httpContext">Контекст HTTP-запроса (используется для доступа к Query string).</param> | ||
| /// <returns> | ||
| /// OkResponse с выбранным адресом сервиса в зависимости от query-параметра id, либо случайно выбранный адрес | ||
| /// сервиса, если query-параметр не задан. | ||
| /// </returns> | ||
| public async Task<Response<ServiceHostAndPort>> 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<ServiceHostAndPort>(currentServices[index].HostAndPort); | ||
| } | ||
|
|
||
| private OkResponse<ServiceHostAndPort> SelectRandomService(List<Service> 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<ServiceHostAndPort>(currentServices[randomIndex].HostAndPort); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<ILogger<QueryBasedLoadBalancer>>(); | ||
| return new QueryBasedLoadBalancer(logger, discoveryProvider.GetAsync); | ||
| }); | ||
|
|
||
| var app = builder.Build(); | ||
|
|
||
| app.UseCors("AllowLocalDev"); | ||
| await app.UseOcelot(); | ||
|
|
||
| await app.RunAsync(); |
38 changes: 38 additions & 0 deletions
38
ResidentialBuilding.Gateway/Properties/launchSettings.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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: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" | ||
| } | ||
| } | ||
| } | ||
| } |
17 changes: 17 additions & 0 deletions
17
ResidentialBuilding.Gateway/ResidentialBuilding.Gateway.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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="..\ResidentialBuilding.ServiceDefaults\ResidentialBuilding.ServiceDefaults.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| }, | ||
| "AllowedHosts": "*" | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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" | ||
| } | ||
| } | ||
| ] | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.