-
Notifications
You must be signed in to change notification settings - Fork 52
Жидяев Дмитрий Лаб. 3 Группа 6513 #128
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
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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
| 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="..\SoftwareProjects\SoftwareProjects.ServiceDefaults\SoftwareProjects.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,54 @@ | ||
| using Ocelot.LoadBalancer.Interfaces; | ||
| using Ocelot.Responses; | ||
| using Ocelot.Values; | ||
|
|
||
| namespace Api.Gateway.LoadBalancers; | ||
|
|
||
| /// <summary> | ||
| /// Балансировщик нагрузки на основе взвешенного случайного выбора (Weighted Random). | ||
| /// Каждой реплике назначается вероятность выбора. При поступлении запроса | ||
| /// реплика выбирается случайно с учётом заданных вероятностей. | ||
| /// Веса задаются в appsettings.json в секции "WeightedRandomWeights". | ||
| /// </summary> | ||
| /// <param name="services">Фабрика для получения списка доступных сервисов.</param> | ||
| /// <param name="configuration">Конфигурация приложения для чтения весов из секции "WeightedRandomWeights".</param> | ||
| public class WeightedRandomLoadBalancer(Func<Task<List<Service>>> services, IConfiguration configuration) : ILoadBalancer | ||
| { | ||
| private readonly double[] _cumulativeWeights = BuildCumulativeWeights( | ||
| configuration.GetSection("WeightedRandomWeights").Get<double[]>() ?? [0.4, 0.3, 0.15, 0.1, 0.05]); | ||
|
|
||
| public string Type => nameof(WeightedRandomLoadBalancer); | ||
|
|
||
| public async Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext httpContext) | ||
| { | ||
| var availableServices = await services(); | ||
|
|
||
| if (availableServices.Count == 0) | ||
| throw new InvalidOperationException("No available downstream services"); | ||
|
|
||
| var index = Array.BinarySearch(_cumulativeWeights, Random.Shared.NextDouble()); | ||
| if (index < 0) index = ~index; | ||
|
|
||
| return new OkResponse<ServiceHostAndPort>( | ||
| availableServices[Math.Min(index, availableServices.Count - 1)].HostAndPort); | ||
| } | ||
|
|
||
| public void Release(ServiceHostAndPort hostAndPort) { } | ||
|
|
||
| /// <summary> | ||
| /// Строит массив кумулятивных весов на основе входных весов. | ||
| /// Каждый элемент результирующего массива равен сумме всех предыдущих весов включительно. | ||
| /// Используется для выбора реплики методом бинарного поиска по случайному числу. | ||
| /// </summary> | ||
| /// <param name="weights">Массив весов для каждой реплики.</param> | ||
| /// <returns>Массив кумулятивных весов.</returns> | ||
| private static double[] BuildCumulativeWeights(double[] weights) | ||
| { | ||
| var total = weights.Sum(); | ||
| var cumulative = new double[weights.Length]; | ||
| cumulative[0] = weights[0] / total; | ||
| for (var i = 1; i < weights.Length; i++) | ||
| cumulative[i] = cumulative[i - 1] + weights[i] / total; | ||
| return cumulative; | ||
| } | ||
| } |
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,32 @@ | ||
| using Api.Gateway.LoadBalancers; | ||
| 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); | ||
| builder.Services.AddOcelot() | ||
| .AddCustomLoadBalancer((sp, _, provider) => | ||
| new WeightedRandomLoadBalancer(provider.GetAsync, sp.GetRequiredService<IConfiguration>())); | ||
|
|
||
| var trustedOrigins = builder.Configuration | ||
| .GetSection("TrustedOrigins") | ||
| .Get<string[]>() ?? []; | ||
|
|
||
| builder.Services.AddCors(options => | ||
| { | ||
| options.AddDefaultPolicy(policy => | ||
| { | ||
| policy.WithOrigins(trustedOrigins) | ||
| .WithMethods("GET") | ||
| .AllowAnyHeader(); | ||
| }); | ||
| }); | ||
|
|
||
| var app = builder.Build(); | ||
| app.UseCors(); | ||
| app.MapDefaultEndpoints(); | ||
| await app.UseOcelot(); | ||
| app.Run(); |
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:64729", | ||
| "sslPort": 44359 | ||
| } | ||
| }, | ||
| "profiles": { | ||
| "http": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": true, | ||
| "applicationUrl": "http://localhost:5025", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "https": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": true, | ||
| "applicationUrl": "https://localhost:7081;http://localhost:5025", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "IIS Express": { | ||
| "commandName": "IISExpress", | ||
| "launchBrowser": true, | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| } | ||
| } | ||
| } |
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,14 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "TrustedOrigins": [ | ||
| "http://localhost:5127", | ||
| "https://localhost:7282" | ||
| ], | ||
| "WeightedRandomWeights": [ 0.30, 0.25, 0.20, 0.15, 0.10 ] | ||
| } |
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": [ | ||
| { | ||
| "UpstreamPathTemplate": "/software-projects", | ||
| "UpstreamHttpMethod": [ "GET" ], | ||
| "DownstreamPathTemplate": "/api/software-projects", | ||
| "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": "WeightedRandomLoadBalancer" | ||
| } | ||
| } | ||
| ] | ||
| } |
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
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": "https://localhost:7081/software-projects" | ||
| } | ||
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,68 @@ | ||
| using Amazon.SimpleNotificationService.Util; | ||
| using File.Service.Storage; | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using System.Text; | ||
|
|
||
| namespace File.Service.Controllers; | ||
|
|
||
| /// <summary> | ||
| /// Контроллер вебхука, принимающий уведомления от SNS-топика | ||
| /// </summary> | ||
| /// <param name="storage">Служба объектного хранилища, в которое сохраняется тело уведомления</param> | ||
| /// <param name="logger">Структурный логгер</param> | ||
| [ApiController] | ||
| [Route("api/sns")] | ||
| public class SnsWebhookController(IObjectStorage storage, ILogger<SnsWebhookController> logger) : ControllerBase | ||
| { | ||
| /// <summary> | ||
| /// Принимает HTTP-запросы от SNS. Подтверждает подписку, если получено сообщение типа | ||
| /// <c>SubscriptionConfirmation</c>, иначе сохраняет полезную нагрузку в объектное хранилище | ||
| /// </summary> | ||
| /// <returns><c>200 OK</c> в любом случае — иначе SNS будет повторять отправку</returns> | ||
| [HttpPost] | ||
| [ProducesResponseType(200)] | ||
| public async Task<IActionResult> Receive() | ||
| { | ||
| logger.LogInformation("SNS webhook invoked"); | ||
| try | ||
| { | ||
| using var reader = new StreamReader(Request.Body, Encoding.UTF8); | ||
| var jsonContent = await reader.ReadToEndAsync(); | ||
| var snsMessage = Message.ParseMessage(jsonContent); | ||
|
|
||
| if (snsMessage.Type == "SubscriptionConfirmation") | ||
| { | ||
| logger.LogInformation("SubscriptionConfirmation received"); | ||
| using var httpClient = new HttpClient(); | ||
| var builder = new UriBuilder(new Uri(snsMessage.SubscribeURL)) | ||
| { | ||
| Scheme = "http", | ||
| Host = "localhost", | ||
| Port = 4566 | ||
| }; | ||
|
|
||
| var response = await httpClient.GetAsync(builder.Uri); | ||
| if (!response.IsSuccessStatusCode) | ||
| { | ||
| var body = await response.Content.ReadAsStringAsync(); | ||
| throw new Exception($"SubscriptionConfirmation returned {response.StatusCode}: {body}"); | ||
| } | ||
|
|
||
| logger.LogInformation("SNS subscription confirmed"); | ||
| return Ok(); | ||
| } | ||
|
|
||
| if (snsMessage.Type == "Notification") | ||
| { | ||
| await storage.UploadProject(snsMessage.MessageText); | ||
| logger.LogInformation("SNS notification successfully processed"); | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Exception while processing SNS notification"); | ||
| } | ||
|
|
||
| return Ok(); | ||
| } | ||
| } | ||
Oops, something went wrong.
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.
Этот адрес я поместил бы в аппсеттинги приложения и брал бы исключительно оттуда