-
Notifications
You must be signed in to change notification settings - Fork 0
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
Transaction management #2
Conversation
This reverts commit 2749ddf.
Makefile
Outdated
@@ -0,0 +1,56 @@ | |||
#SHELL = /bin/bash | |||
.PHONY: autotest dep test race lint gen cover statictest dev-up dev-down accrual dev-autotest |
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.
PHONY лучше прописывать отдельно перед каждым таргетом.
Будет легче разрешать конфликты при мерджах + при большом кол-ве таргетов становится неудобно поддерживать общий PHONY
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.
прописал перед каждым
config/app.go
Outdated
|
||
type ( | ||
App struct { | ||
Address `env:"RUN_ADDRESS"` |
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.
Встраивание не для наследования полей, а для наследования поведения. Лучше делать обычные поля, т.к. встраивание может начать путать и приводить к ошибкам при вызове методов.
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.
поправил
} | ||
} | ||
|
||
func errorJSON(w http.ResponseWriter, err error, status int, logger logger.AppLogger) { |
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.
Статус лучше определять по типу ошибки с использованием конструкции errors.Is
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.
теперь все коды сопоставляются с ошибками
Data interface{} `json:"data,omitempty"` | ||
} | ||
|
||
func writeJSON(w http.ResponseWriter, status int, contentType string, data any, logger logger.AppLogger, headers ...http.Header) { |
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.
Не стоит передавать сюда content-type, всегда будет json
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.
убрал
var ctx = context.Background() | ||
var err error | ||
|
||
orderNumberRaw, err = io.ReadAll(r.Body) |
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.
Нужно закрывать тело обязательно
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.
поправил
internal/usecase/syncer/syncer.go
Outdated
} | ||
|
||
func (s *syncer) Run() error { | ||
s.tick <- struct{}{} // init tick |
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.
Лучше использовать time.Ticker
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.
переписал с использованием time.Ticker
internal/usecase/syncer/syncer.go
Outdated
} | ||
|
||
func (s *syncer) Shutdown(ctx context.Context) error { | ||
once.Do(func() { |
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.
once должна быть переменной syncer, а не модуля, т.к. исходя из дизайна ликеров может быть несколько
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.
поправил
internal/usecase/syncer/syncer.go
Outdated
} | ||
|
||
func (s *syncer) sync() error { | ||
orders, err := s.orderRepo.GetUnprocessed(context.TODO()) |
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.
Контекст TODO не должен присутствовать в итоговом коде
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.
Упустил. Исправил.
internal/models/user.go
Outdated
type User struct { | ||
Login string `json:"login" db:"login"` | ||
Password string `json:"password" db:"password"` | ||
Balance float64 `db:"balance"` |
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.
Не стоит работать с денежными единицами во float64. Из-за неточности арифметических операций могут потеряться копейки и быть юридические проблемы
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.
Теперь храню в
type Money struct {
Amount Amount
}
type Amount uint64
internal/usecase/syncer/syncer.go
Outdated
|
||
// if the new status is valid for accrual - change user balance | ||
if newStatus == "PROCESSED" { | ||
user, err := s.userRepo.Get(ctx, models.User{Login: orders[i].User}) |
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.
Без установки блокировки возможна потеря списаний.
Например, когда пользователь запрашивает списание баллов и мы одновременно обрабатываем его заказ.
Необходимо выполнять списание баллов в транзакции.
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.
запихнул в транзакцию с использованием менеджера транзакций
No description provided.