Skip to content
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

Инкремент №23 #21

Merged
merged 8 commits into from
Nov 12, 2024
Merged

Инкремент №23 #21

merged 8 commits into from
Nov 12, 2024

Conversation

ex0rcist
Copy link
Owner

@ex0rcist ex0rcist commented Nov 10, 2024

По шифрованию: в пачке писал вопрос, четкого ответа не дали. В итоге сделал шифрование chunk-ами целиком под RSA. Это медленнее, чем если бы мы шифровали AES тело, а RSA только ключи AES. Но быстрее в реализации, т.к. проект учебный, то я не вижу смысла тут особо заморачиваться, особенно в контексте подготовки к собесам и переворачиваниям деревьев.

По json-конфигу: там есть некоторые различия и нестыковки в задании, я сделал чтение из файла, если передан аргумент. При этом аргумент я парсил вручную через os.Args и перед парсингом pflags, потому что согласно доке это можно сделать один раз. А нам надо сначала выяснить, есть ли в аргументах вообще файл конфига. Вообщем как по мне абсолютно дурацкое требование, я в реальной жизни за 15 лет никогда не сталкивался с такими трёхуровневыми костылями конфигурации, надеюсь что не столкнусь.

По сигналам: плавная остановка сервера уже была реализована раньше, добавил плавную остановку агента

Покрытие:

$ make unit-test
...
total: (statements) 71.6%

@ex0rcist ex0rcist requested a review from Perederey November 11, 2024 18:05
Copy link
Collaborator

@Perederey Perederey left a comment

Choose a reason for hiding this comment

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

Привет! Отлично справился понимаю твою боль, но шифрование оно такое :)

return err
}
a.Exporter = exporter

Copy link
Collaborator

Choose a reason for hiding this comment

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

Выдели константы для сигналов в отдельную группу для лучшей читаемости:

var shutdownSignals = []os.Signal{
    syscall.SIGINT,
    syscall.SIGTERM,
    syscall.SIGQUIT,
}


a.wg.Wait()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Отлично реализован graceful shutdown

ReportInterval int `env:"REPORT_INTERVAL"`
RateLimit int `env:"RATE_LIMIT"`
Secret entities.Secret `env:"KEY"`
Address entities.Address `env:"ADDRESS" json:"address"`
Copy link
Collaborator

Choose a reason for hiding this comment

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

Тут для всех интервалов, используй time.Duration вместо int для интервалов в конфигурации

// Metric collecting agent (mr. Bond?).
type Agent struct {
Config *Config
Stats *Stats
Exporter exporter.Exporter

interrupt chan os.Signal

wg sync.WaitGroup
}

// Agent config.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Конфигурацию лучше выносить в отдельный пакет. Это упростит тестирование и переиспользование. Например, можно сделать так:

package config

type Config struct {
    Host string
    Port int
}

func New() *Config {
    return &Config{
        Host: "localhost",
        Port: 8080,
    }
}

// В основном коде
cfg := config.New()

Кстати, можно применить паттерн Options для гибкой настройки конфига. Это сделает код более поддерживаемым.

@@ -0,0 +1,162 @@
package security
Copy link
Collaborator

Choose a reason for hiding this comment

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

Хорошо структурированный код с четким разделением ответственности получился у тебя 

@ex0rcist ex0rcist merged commit eb97d12 into main Nov 12, 2024
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants