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

Инкременты №16-18 #16

Merged
merged 9 commits into from
Oct 30, 2024
Merged

Инкременты №16-18 #16

merged 9 commits into from
Oct 30, 2024

Conversation

ex0rcist
Copy link
Owner

@ex0rcist ex0rcist commented Oct 21, 2024

В этом pr:

  • чуть доработал внутреннее устройство сервера (с прицелом на grpc дальше по курсу), добавил graceful shutdown
  • добавил Makefile
  • также перенес часть функционала в pkg для корректной генерации документации
  • в процессе написания документации понял, что errToStatus не очень удачное решение и его лучше переписать под явную обработку ошибок, но не стал это делать в рамках этого PR чтобы не забивать diff
  1. Извиняюсь, что оформил PR в этот раз не по правилам. После гофермарта забыл про деление на ветки и отдельные PR :( Плюс, не думал что так разрастется из-за комментариев.

  2. Тесты:
    $ make unit-tests

...
total: (statements) 65.7%

  1. Форматирование:
    Т.к. я пишу в vscode с включенным gopls, он автоматически форматирует весь код в соответствии со стандартом, так что форматирование через gofmt ничего не поменяло:
$ gofmt -w .
$ git status
Текущая ветка: iter17
Эта ветка соответствует «origin/iter17».
  1. Профилирование:
    Сначала снимал профили просто в случайный момент времени, так:
$ sleep 30 && curl -s http://0.0.0.0:8081/debug/pprof/heap > profiles/base.pprof
$ sleep 30 && curl -s http://0.0.0.0:8081/debug/pprof/heap > profiles/result.pprof

Самыми большими нодами на графике были ноды gzip, поэтому решил попробовать заменить его на на https://github.com/klauspost/compress. Если я правильно понял, то снимок кучи выглядит по-разному в разные моменты времени, несмотря на то, что агент посылает запросы на сервер с интервалом в 1 секунду. Не всегда эти профили были похожи друг на друга (в graph и flamegraph). Но удалось поймать схожие снимки, и сравнивал их. Потом я все же решил что сравнение не совсем честное, и доработал профайлер таким образом, чтобы он вызывался в одни и те же моменты времени (один раз, на третий вызов BatchUpdateMetricsJSON). Затем сохранил их по очереди и сравнил, новый компрессор показывает отрицательные числа в утилите сравнения (go tool pprof -top -diff_base=profiles/base.prof profiles/result.prof), т.е. потребляет меньше памяти.
Также он показывает прирост по бенчмарку:

$ go test -bench=. ./internal/middleware/ -benchmem
goos: darwin
goarch: arm64
pkg: github.com/ex0rcist/metflix/internal/middleware
BenchmarkCompression-8             15694             76675 ns/op         1207112 B/op         41 allocs/op

$ go test -bench=. ./internal/middleware/ -benchmem
goos: darwin
goarch: arm64
pkg: github.com/ex0rcist/metflix/internal/middleware
BenchmarkCompression-8             20361             60147 ns/op          820657 B/op         38 allocs/op
  1. Документация:
  • swagger-документация для эндпойнтов получается при сборке проекта (make build) и доступна через swagger на http://localhost:8080/swagger/index.html. В бою её, конечно, нужно генерировать отдельно и складывать куда-то в вики, например.
  • godoc-документация с Example() доступна через make:
$ make godoc
Project documentation is available at:
http://127.0.0.1:3000/pkg/github.com/ex0rcist/metflix/pkg/
  1. Автотесты: забрал 16-18 автотесты из сокращателя (дурак). В моках pgx оставил stub-комментарии, не вижу смысла тут на них тратить время. Все остальное исправил

@ex0rcist ex0rcist changed the title wip Iter18 Инкременты №16-18 Oct 22, 2024
@ex0rcist ex0rcist requested a review from Perederey October 22, 2024 13: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.

Привет! Ты отлично поработал над кодом и над документацией API. Однако есть несколько моментов, которые стоит улучшить:

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

В целом, ты на правильном пути! Продолжай в том же духе

var _ StorageService = Service{}

// Service struct, containing storage
type Service struct {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Сервис хранения слишком тесно связан с конкретной реализацией хранилища, попробуй разделить

Copy link
Owner Author

Choose a reason for hiding this comment

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

Здесь не догнал, как именно связан? Хранилище имеет интерфейсный тип, сервис ничего не знает вроде как о конкретном типе хранилища. Или я до конца не понял?

// @Tags Metrics
// @Router /updates [post]
// @Summary Push list of metrics data as JSON
// @ID metrics_json_update_list
Copy link
Collaborator

Choose a reason for hiding this comment

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

Назови проще UpdateMetricsBatch

@@ -16,6 +16,7 @@

var _ MetricsStorage = DatabaseStorage{}

// DB Storage
Copy link
Collaborator

Choose a reason for hiding this comment

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

Лучше PostgresStorage

@@ -25,6 +27,7 @@ func (r Retrier) Run() error {
)
}

// Retrier constructor
Copy link
Collaborator

Choose a reason for hiding this comment

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

Из фишек гоу, в структуре можно использовать функциональные опции для более гибкой настройки. Типа такого:

type RetryOption func(*Retrier)

func WithDelays(delays []time.Duration) RetryOption {
    return func(r *Retrier) {
        r.delays = delays
    }
}

func NewRetrier(payloadFn func() error, retryIfFn func(error) bool, opts ...RetryOption) *Retrier {
    r := &Retrier{
        payloadFn: payloadFn,
        retryIfFn: retryIfFn,
    }
    for _, opt := range opts {
        opt(r)
    }
    return r
}

Это позволит более гибко настраивать Retrier при создании.

@@ -58,6 +69,18 @@
Copy link
Collaborator

Choose a reason for hiding this comment

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

Отличная работа по добавлению документации для Swagger 💪

}

// Singleton
func GetProfiler() *Profiler {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Отличное решение использовать синглтон для профайлера 👍

@@ -0,0 +1,54 @@
//nolint:gocritic
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 08eb4a0 into main Oct 30, 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