Skip to content

Томашайтис Павел Лаб. 3 Группа 6513#113

Open
Tomashaytis wants to merge 30 commits intoitsecd:mainfrom
Tomashaytis:main
Open

Томашайтис Павел Лаб. 3 Группа 6513#113
Tomashaytis wants to merge 30 commits intoitsecd:mainfrom
Tomashaytis:main

Conversation

@Tomashaytis
Copy link
Copy Markdown

ФИО: Томашайтис Павел
Номер группы: 6513
Номер лабораторной: 3
Номер варианта: 52
Краткое описание предметной области: Учебный курс
Краткое описание добавленных фич:

  • Реализовано взаимодействие с брокером сообщений SNS (LocalStack).
  • Добавлен файловый сервис для сохранения сгенерированных контрактов в объектном хранилище S3 (LocalStack).
  • Реализованы интеграционные тесты приложения.

Tomashaytis and others added 27 commits February 21, 2026 15:36
…но использование собственного балансировщика нагрузки
…жность публикации сообщений в брокер. Добавлена работа с объектным хранилищем S3 через Localstack.
@github-actions github-actions bot added In progress Код в процессе проверки Lab 3 Лабораторная №3. Интеграционное тестирование labels Apr 15, 2026
@github-actions github-actions bot requested a review from alxmcs April 15, 2026 07:57
/// <param name="logger"></param>
/// <param name="client"></param>
/// <param name="configuration"></param>
public class SnsPublisherService<T>(ILogger<SnsPublisherService<T>> logger, IAmazonSimpleNotificationService client, IConfiguration configuration) : IPublisherService<T>
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если честно, то тут можно было бы обойтись без дженерика

?? throw new KeyNotFoundException("SNS topic link was not found in configuration");

/// <inheritdoc/>
public async Task<bool> SendMessage(int id, T entity, CancellationToken cancellationToken)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ведь тут просто можно использовать object entity
Какого-то случая контрвариативности у тебя нет, ведь в di регистрируется только один экземпляр службы для Course
И каких-либо ограничений на T не накладывается

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Но в целом, как некоторое предвосхищение потенциального расширения функционала сервиса, если он, например, начнет заниматься генерацией контрактов разных типов, это вполне имеет право на существование.
Так что давай оставим все как есть

Comment thread CourseManagement.AppHost/AppHost.cs Outdated
Comment on lines +6 to +29
var apiServiceConfig = builder.Configuration.GetSection("ApiService");
var ports = apiServiceConfig.GetSection("Ports").Get<List<int>>() ?? [];

// Read configuration for Api Gateway
var apiGatewayConfig = builder.Configuration.GetSection("ApiGateway");
var gatewayPort = apiGatewayConfig.GetValue<int>("Port");

// Read configuration for AWS
var awsConfig = builder.Configuration.GetSection("AWS");
var accessKey = awsConfig.GetValue<string>("AccessKeyId") ?? "none";
var secretKey = awsConfig.GetValue<string>("SecretAccessKey") ?? "none";
var region = awsConfig.GetValue<string>("Region") ?? "none";

// Read configuration for AWS Resources
var awsResourcesConfig = awsConfig.GetSection("Resources");
var topicName = awsResourcesConfig.GetValue<string>("TopicName") ?? "none";
var bucketName = awsResourcesConfig.GetValue<string>("BucketName") ?? "none";
var snsTopicArn = awsResourcesConfig.GetValue<string>("SNSTopicArn") ?? "none";
var snsEndpointUrl = awsResourcesConfig.GetValue<string>("SNSEndpointURL") ?? "none";

// Read configuration for Localstack, S3, SNS
var localStackServiceUrl = builder.Configuration.GetSection("LocalStack").GetValue<string>("ServiceURL") ?? "none";
var s3ServiceUrl = builder.Configuration.GetSection("S3").GetValue<string>("ServiceURL") ?? "none";
var snsServiceUrl = builder.Configuration.GetSection("SNS").GetValue<string>("ServiceURL") ?? "none";
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отчасти из-за этого я и рекомендовал пользоваться сloud formation
Поскольку я не навязываю его использование, можно оставить и так
Но с сloud formation было бы меньше кода

Comment thread CourseManagement.AppHost/AppHost.cs Outdated
Comment on lines +37 to +46
var localstack = builder.AddContainer("localstack", "localstack/localstack:3.8.0")
.WithEndpoint(port: 4566, targetPort: 4566, name: "localstack", scheme: "http")
.WithEnvironment("SERVICES", "sns,s3")
.WithEnvironment("AWS_ACCESS_KEY_ID", accessKey)
.WithEnvironment("AWS_SECRET_ACCESS_KEY", secretKey)
.WithEnvironment("AWS_DEFAULT_REGION", region)
.WithEnvironment("SKIP_SIGNATURE_VALIDATION", "1")
.WithContainerRuntimeArgs(
"--add-host", "host.docker.internal:host-gateway"
);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А вот это уже надо править - у aspire есть библиотека для хостинга localstack

Comment thread CourseManagement.AppHost/AppHost.cs Outdated
Comment on lines +49 to +59
var localstackInit = builder.AddContainer("localstack-init", "amazon/aws-cli")
.WithArgs(
$"--endpoint-url={localStackServiceUrl}",
"sns", "create-topic",
"--name", topicName,
"--region", region
)
.WithEnvironment("AWS_ACCESS_KEY_ID", accessKey)
.WithEnvironment("AWS_SECRET_ACCESS_KEY", secretKey)
.WithEnvironment("AWS_DEFAULT_REGION", region)
.WaitFor(localstack);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Помимо того, что там будет телеметрия, не придется вручную настраивать локалстак через поднятие контейнера с cli

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AWS" Version="13.0.0" />
<PackageReference Include="Aspire.Hosting.Redis" Version="13.1.1" />
<PackageReference Include="LocalStack.Aspire.Hosting" Version="13.1.0" />
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Загадочно - нужная библиотека у тебя добавлена в проект, но ты ей не пользуешься

Comment thread CourseManagement.Storage/Program.cs Outdated
Comment on lines +19 to +24
var configuration = builder.Configuration;
var region = configuration["AWS:Region"] ?? throw new KeyNotFoundException("AWS region was not found in configuration");
var accessKey = configuration["AWS:AccessKeyId"] ?? throw new KeyNotFoundException("AWS access key ID link was not found in configuration");
var secretKey = configuration["AWS:SecretAccessKey"] ?? throw new KeyNotFoundException("AWS secret access key was not found in configuration");
var s3Url = configuration["S3:ServiceURL"] ?? throw new KeyNotFoundException("S3 service URL was not found in configuration");
var snsUrl = configuration["SNS:ServiceURL"] ?? throw new KeyNotFoundException("SNS service URL was not found in configuration");
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По идее, у тебя есть клиенская библиотека localstack, так что можно упростить регистрацию служб через
builder.Services.AddLocalStack(builder.Configuration);, если параметры подключения в конфигурации прописаны в ожидаемом для localstack формате

Comment thread CourseManagement.Storage/Program.cs Outdated
Comment on lines +27 to +42
builder.Services.AddSingleton<IAmazonS3>(
new AmazonS3Client(accessKey, secretKey, new AmazonS3Config
{
ServiceURL = s3Url,
UseHttp = true,
AuthenticationRegion = region
})
);
builder.Services.AddSingleton<IAmazonSimpleNotificationService>(
new AmazonSimpleNotificationServiceClient(accessKey, secretKey, new AmazonSimpleNotificationServiceConfig
{
ServiceURL = snsUrl,
UseHttp = true,
AuthenticationRegion = region
})
);
Copy link
Copy Markdown
Collaborator

@alxmcs alxmcs Apr 16, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У тебя, вроде бы, добавлены все необходимые пакеты, чтобы не издеваться над собой и просто написать:

builder.Services.AddAwsService<IAmazonS3>();
builder.Services.AddAwsService<IAmazonSimpleNotificationService>();

Все параметры подтянутся из localstack

Comment thread CourseManagement.sln Outdated
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кстати, раз уж ты живешь на 18 студии и 10 дотнете, то можно перейти на slnx
dotnet sln CourseManagement.sln migrate
Только не забудь удалить старый sln

@Tomashaytis
Copy link
Copy Markdown
Author

Изменил структуру проекта, добавил cloud formation.

@Tomashaytis Tomashaytis requested a review from alxmcs April 18, 2026 08:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

In progress Код в процессе проверки Lab 3 Лабораторная №3. Интеграционное тестирование

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants