Skip to content

Казаков Андрей Лаб. 3 Группа 6513#85

Open
Gironape wants to merge 27 commits intoitsecd:mainfrom
Gironape:main
Open

Казаков Андрей Лаб. 3 Группа 6513#85
Gironape wants to merge 27 commits intoitsecd:mainfrom
Gironape:main

Conversation

@Gironape
Copy link
Copy Markdown

@Gironape Gironape commented Apr 3, 2026

ФИО: Казаков Андрей
Номер группы: 6513
Номер лабораторной: 3
Номер варианта: 43
Краткое описание предметной области: Сотрудник компании
Краткое описание добавленных фич: Добавлен SNS брокер + MinIO хранилище + тесты

Стыдно должно быть, но пока рано
Не судите строго, я pycharman
С каждой строчкой я все дальше от бога
Сделал исправления
Пожалуйста, не ругайтесь на C#-инвалида (на меня)
Добавил недостающее summary
Надеюсь, я делаю что-то похожее на правду
Скорее всего где-то накосячил, не ругайтесь на меня
Убрал CORS в API, исправил недочет в AppHost.cs и обновил пакеты до версии 9.5.0
Потихоньку делаю
Написал всякой фигни, понял, что не работает, теперь переделываю
Вроде, все работает, осталось немного доделать
Посмотрел не свой вариант и увидел, что у меня Minio, а не Localstack
Вроде, правильно должно быть
Еще раз прошу не осуждать, я пытаюсь развиваться в этом предмете, правда...
@github-actions github-actions bot added In progress Код в процессе проверки Lab 3 Лабораторная №3. Интеграционное тестирование labels Apr 3, 2026
@github-actions github-actions bot requested a review from alxmcs April 3, 2026 21:25
Comment thread CompanyEmployee.Api/CompanyEmployee.Api.csproj Outdated
Comment thread CompanyEmployee.FileService/Consumers/EmployeeGeneratedConsumer.cs Outdated
Comment thread CompanyEmployee.FileService/Services/MinioStorageService.cs Outdated
Comment thread CompanyEmployee.FileService/Services/MinioStorageService.cs Outdated
Comment thread CompanyEmployee.FileService/CompanyEmployee.FileService.csproj Outdated
Comment thread CompanyEmployee.FileService/Program.cs Outdated
Comment thread CompanyEmployee.AppHost/AppHost.cs Outdated
Comment thread CompanyEmployee.FileService/Program.cs Outdated
Comment thread CompanyEmployee.IntegrationTests/BasicTest.cs
Comment thread CompanyEmployee.IntegrationTests/BasicTest.cs Outdated
Gironape added 2 commits April 9, 2026 14:30
Пока не готово, но уже что-то
Повозился, вроде, сделал правильно SNS и без SQS (Надеюсь..)
Также исправил интеграционные тесты, и сделал небольшие требуемые исправления
@Gironape Gironape requested a review from alxmcs April 10, 2026 19:17
Copy link
Copy Markdown
Collaborator

@alxmcs alxmcs left a comment

Choose a reason for hiding this comment

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

Ситуация:
Image
Данные генерируются, sns сообщения отправляются, а файлов в хранилище в итоге все равно ноль.
Предположу, что я знаю, в чем проблема. Рекомендую зайти завтра на лекцию, чтобы тоже быть в курсе

IConfiguration configuration,
ILogger<SnsPublisherService> logger)
{
private readonly string? _topicArn = configuration["SNS:TopicArn"] ?? "arn:aws:sns:us-east-1:000000000000:employee-events";
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.

Не надо хардкодить параметры работы бекенда. У любого безопасника, который будет прогонять статический анализатор по твоему коду, произойдет кровоизлияние в мозг от этой строки.

Пароли и апи ключи же ты не хардкодишь, а чем уникальный глобальный идентификатор aws-ного ресурса хуже?

Лучше выкинуть исключение, что требуемых параметров в конфигурации не нашлось

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.

Я стесняюсь спросить, а что делать людям, которые не на винде будут поднимать твои сервисы?

Ладно, пофигу, оставляй так. Но это одна из причин, почему я советовал пользоваться каким-нибудь IaC-ом типа CloudFormation

Comment thread README.md 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.

А как же описание проекта...

Comment thread CompanyEmployee.FileService/Properties/launchSettings.json
Comment thread CompanyEmployee.FileService/Program.cs Outdated
Comment on lines +49 to +83
app.MapPost("/api/sns/notification", async (HttpRequest request, IStorageService storage, ILogger<Program> logger) =>
{
using var reader = new StreamReader(request.Body);
var body = await reader.ReadToEndAsync();

using var doc = JsonDocument.Parse(body);
var type = doc.RootElement.GetProperty("Type").GetString();

if (type == "SubscriptionConfirmation")
{
var subscribeUrl = doc.RootElement.GetProperty("SubscribeURL").GetString();
logger.LogInformation("������������� ��������: {Url}", subscribeUrl);

using var client = new HttpClient();
await client.GetAsync(subscribeUrl);

return Results.Ok(new { message = "Subscription confirmed" });
}

if (type == "Notification")
{
var messageJson = doc.RootElement.GetProperty("Message").GetString();
var employee = JsonSerializer.Deserialize<Employee>(messageJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

if (employee != null)
{
var fileName = $"employee_{employee.Id}.json";
var content = JsonSerializer.SerializeToUtf8Bytes(employee);
await storage.SaveFileAsync(bucketName, fileName, content);
logger.LogInformation("��������� {Id} �������� � MinIO", employee.Id);
}
}

return Results.Ok();
});
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.

Метод на 34 строки - это нечто противоположное концепции minimal api. Предлагаю либо вынести этот метод в отдельную службу, либо сделать классический контроллер

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.

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

@Gironape
Copy link
Copy Markdown
Author

Спасибо большое, обязательно зайду на лекцию завтра, чтобы все исправить нормально и больше не мозолить вам глаза своим PR. С Пасхой!

Вроде, я поправил все, что нужно было, все сохраняется, swagger добавил для fileservice, сделал end to end тест, и изменил фикстуру. Вроде, даже праймари конструкторы везде... Надеюсь, я не зря не спал эту ночь и еще лекцию прослушал, и ваш код посмотрел... Здоровья всем нам
@Gironape Gironape requested a review from alxmcs April 15, 2026 07:34
Comment on lines -10 to -13
/// <param name="generator">Генератор сотрудников.</param>
/// <param name="cache">Кэш Redis.</param>
/// <param name="snsPublisher">Публикатор SNS.</param>
/// <param name="logger">Логгер.</param>
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.

Ну вот это ты, конечно, зря снес

private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };

private readonly string _topicArn = configuration["SNS:TopicArn"]
?? "arn:aws:sns:us-east-1:000000000000:employee-events";
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 CompanyEmployee.AppHost/AppHost.cs Outdated
Comment on lines +8 to +14
.WithEndpoint(port: 9000, targetPort: 9000, name: "api", scheme: "http")
.WithEndpoint(port: 9001, targetPort: 9001, name: "console", scheme: "http");
.WithEndpoint(port: 9000, targetPort: 9000, scheme: "http", name: "minio-api")
.WithEndpoint(port: 9001, targetPort: 9001, scheme: "http", name: "minio-console");
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 CompanyEmployee.AppHost/AppHost.cs Outdated
Comment on lines +16 to +24
var localstack = builder.AddContainer("localstack", "localstack/localstack:3.8.0")
.WithEndpoint(port: 4566, targetPort: 4566, name: "localstack", scheme: "http")
.WithEndpoint(port: 4566, targetPort: 4566, scheme: "http", name: "localstack")
.WithEnvironment("SERVICES", "sns")
.WithEnvironment("AWS_ACCESS_KEY_ID", "test")
.WithEnvironment("AWS_SECRET_ACCESS_KEY", "test")
.WithEnvironment("AWS_DEFAULT_REGION", "us-east-1");
.WithEnvironment("AWS_DEFAULT_REGION", "us-east-1")
.WithEnvironment("SKIP_SSL_CERT_DOWNLOAD", "1")
.WithEnvironment("LOCALSTACK_HOST", "localhost.localstack.cloud")
.WithLifetime(ContainerLifetime.Persistent);
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 on lines -9 to -10
/// <param name="minioClient">Клиент MinIO.</param>
/// <param name="logger">Логгер.</param>
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 CompanyEmployee.FileService/Program.cs Outdated
{
await minioClient.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucket));
Console.WriteLine($"����� {bucket} ������");
logger.LogInformation("Bucket {BucketName} created successfully", bucket);
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.

Как будто подобный код просится быть вынесенным в IStorageService в виде отдельного метода

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.

На старте этого приложения я бы вызвал инициализацию подписки на sns

/// <summary>
/// Однократно инициализирует SNS топик и подписку в LocalStack.
/// </summary>
public async Task InitializeSnsOnce()
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.

Чтобы, как минимум, в интеграционных тестах не заниматься этим

return metadata != null ? Results.Ok(metadata) : Results.NotFound();
});

app.Run(); No newline at end of file
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.

А также, чтобы подписка на sns работала в отладке и продакшене
Потому что сейчас ее не происходит, так что паблиш сообщения происходит в никуда:
Image

Я устал, босс...
@Gironape Gironape requested a review from alxmcs April 16, 2026 10:50
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