Учесть замечания ревью: читать timestamptz в UTC, встроить списки колонок, не требовать каноническую PHC-строку, уточнить замеры отказов
This commit is contained in:
@@ -132,8 +132,8 @@ CI. `.github/workflows/app.yml`: unit-тесты с race detector (на runner
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| Полный рестарт: `docker compose stop` и `up -d --wait` (хук persistence) | те же данные и тот же токен | PASS, все три процесса перезапущены | весь тест с хуком ~15 с; потерь нет |
|
||||
| `docker compose stop valkey` | 503 на защищённые запросы и вход, ready 503, регистрация работает | 503 за 1.2 с (дозвон ограничен 1 с; DNS Docker для остановленного контейнера отвечает ~4 с), `POST /users` 201, в логе `cause: dial tcp: lookup valkey: i/o timeout` | после `start` тот же токен 200: сессии восстановлены из AOF |
|
||||
| `docker compose stop postgres` | 503 на операции с данными, ready 503 | 503 за 0.2 с, в логе причина подключения | после `start` 200 без перезапуска API: пул переподключается |
|
||||
| `docker compose stop valkey` | 503 на защищённые запросы и вход, ready 503, регистрация работает | 503 за 1.2 с (дозвон ограничен 1 с; без ограничения поиск имени остановленного контейнера в DNS Docker не укладывается в дедлайн запроса 5 с), `POST /users` 201, в логе `cause: dial tcp: lookup valkey: i/o timeout` | после `start` тот же токен 200: сессии восстановлены из AOF |
|
||||
| `docker compose stop postgres` | 503 на операции с данными, ready 503 | первый запрос — 503 за 0.2 с (соединение из пула уже разорвано), следующие — за 1.2 с (новое соединение ждёт поиск имени, ограниченный 1 с); в логе причина подключения | после `start` 200 без перезапуска API: пул переподключается |
|
||||
| PostgreSQL на паузе (`docker pause`, тест) | запрос не висит дольше дедлайна | 503 при дедлайне 300 мс, ready 503 | — |
|
||||
| `SESSION_TTL_SECONDS=2` | сессия истекает | 200 сразу, 401 Bearer через 3 с | — |
|
||||
| Ввод, который PostgreSQL не может хранить: NUL в `display_name`/`title`/`text`, NUL или не-UTF-8 в Basic username | 400 / 401, не 500 | 400 и 401 (проверка в приложении) | — |
|
||||
|
||||
@@ -31,10 +31,6 @@ func NewChats(pool *pgxpool.Pool) *Chats {
|
||||
return &Chats{pool: pool}
|
||||
}
|
||||
|
||||
// chatWithMembers selects the projection from a chats row aliased c.
|
||||
const chatWithMembers = `c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)`
|
||||
|
||||
func (r *Chats) Create(ctx context.Context, c chat.Chat, memberIDs []uuid.UUID) error {
|
||||
return postgres.Classify(pgx.BeginFunc(ctx, r.pool, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx,
|
||||
@@ -53,7 +49,8 @@ func (r *Chats) Create(ctx context.Context, c chat.Chat, memberIDs []uuid.UUID)
|
||||
|
||||
func (r *Chats) GetForMember(ctx context.Context, chatID, userID uuid.UUID) (chat.ChatWithMembers, error) {
|
||||
row := r.pool.QueryRow(ctx, `
|
||||
SELECT `+chatWithMembers+`
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)
|
||||
FROM chats c
|
||||
WHERE c.id = $1
|
||||
AND EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
@@ -81,7 +78,8 @@ func (r *Chats) IsMember(ctx context.Context, chatID, userID uuid.UUID) (bool, e
|
||||
|
||||
func (r *Chats) ListByMember(ctx context.Context, userID uuid.UUID, after *uuid.UUID, limit int) ([]chat.ChatWithMembers, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT `+chatWithMembers+`
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)
|
||||
FROM chat_members own
|
||||
JOIN chats c ON c.id = own.chat_id
|
||||
WHERE own.user_id = $1
|
||||
@@ -106,7 +104,6 @@ func scanChat(row pgx.Row) (chat.ChatWithMembers, error) {
|
||||
if err := row.Scan(&c.ID, &c.Title, &c.CreatedAt, &c.MemberIDs); err != nil {
|
||||
return chat.ChatWithMembers{}, err
|
||||
}
|
||||
c.CreatedAt = c.CreatedAt.UTC()
|
||||
return c, nil
|
||||
}
|
||||
|
||||
@@ -147,7 +144,6 @@ func (r *Messages) ListByChat(ctx context.Context, chatID uuid.UUID, after *uuid
|
||||
messages, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (chat.Message, error) {
|
||||
var m chat.Message
|
||||
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
return m, err
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -10,9 +10,7 @@ import (
|
||||
const keyUserID = "messenger.user_id"
|
||||
|
||||
// SetUserID records the authenticated caller for the handlers behind the
|
||||
// authentication middleware and for the access log. It lives here rather
|
||||
// than in the auth package because the access log needs it and the business
|
||||
// modules must not depend on auth.
|
||||
// authentication middleware and for the access log.
|
||||
func SetUserID(c *gin.Context, id uuid.UUID) {
|
||||
c.Set(keyUserID, id)
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ func Verify(encoded, plain string) (bool, error) {
|
||||
var memory, time uint32
|
||||
var parallelism uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, ¶llelism); err != nil ||
|
||||
memory == 0 || time == 0 || parallelism == 0 || params(memory, time, parallelism) != parts[3] {
|
||||
memory == 0 || time == 0 || parallelism == 0 {
|
||||
return false, ErrMalformed
|
||||
}
|
||||
salt, err := b64.DecodeString(parts[4])
|
||||
|
||||
@@ -14,7 +14,9 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
@@ -40,9 +42,10 @@ func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
||||
}
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.ConnConfig.ConnectTimeout = connectTimeout
|
||||
// pgconn applies ConnectTimeout to dialling but resolves the host name
|
||||
// before that with the caller's context. Docker DNS takes seconds to give
|
||||
// up on a stopped container, so the lookup gets the same bound.
|
||||
// Unlike net.Dialer, pgx resolves the host before ConnectTimeout starts.
|
||||
// Docker DNS takes seconds to give up on a stopped container: unbounded,
|
||||
// every request would wait out its deadline and log only "context
|
||||
// deadline exceeded" instead of the failed lookup.
|
||||
cfg.ConnConfig.LookupFunc = func(ctx context.Context, host string) ([]string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, connectTimeout)
|
||||
defer cancel()
|
||||
@@ -50,6 +53,16 @@ func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(statementTimeout.Milliseconds(), 10)
|
||||
cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = strconv.FormatInt(idleInTxTimeout.Milliseconds(), 10)
|
||||
// The application keeps every time in UTC; pgx would otherwise scan
|
||||
// timestamptz into time.Local.
|
||||
cfg.AfterConnect = func(_ context.Context, conn *pgx.Conn) error {
|
||||
conn.TypeMap().RegisterType(&pgtype.Type{
|
||||
Name: "timestamptz",
|
||||
OID: pgtype.TimestamptzOID,
|
||||
Codec: &pgtype.TimestamptzCodec{ScanLocation: time.UTC},
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
|
||||
@@ -31,6 +31,16 @@ func TestMain(m *testing.M) {
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func TestPoolScansTimestamptzInUTC(t *testing.T) {
|
||||
var got time.Time
|
||||
if err := db.Pool.QueryRow(context.Background(), `SELECT now()`).Scan(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Location() != time.UTC {
|
||||
t.Fatalf("timestamptz scanned in %v, want UTC", got.Location())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateIsRepeatable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
applied, err := postgres.Migrate(ctx, db.Pool)
|
||||
|
||||
@@ -16,8 +16,6 @@ import (
|
||||
"messenger/internal/user"
|
||||
)
|
||||
|
||||
const userColumns = `id, username, display_name, password_hash, created_at`
|
||||
|
||||
type Users struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
@@ -32,7 +30,7 @@ func NewUsers(pool *pgxpool.Pool) *Users {
|
||||
// concurrent registrations of one username cannot both succeed.
|
||||
func (r *Users) Create(ctx context.Context, u user.User) error {
|
||||
_, err := r.pool.Exec(ctx,
|
||||
`INSERT INTO users (`+userColumns+`) VALUES ($1, $2, $3, $4, $5)`,
|
||||
`INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`,
|
||||
u.ID, u.Username, u.DisplayName, u.PasswordHash, u.CreatedAt)
|
||||
if postgres.IsUniqueViolation(err, "users_username_key") {
|
||||
return user.ErrUsernameTaken
|
||||
@@ -44,11 +42,11 @@ func (r *Users) Create(ctx context.Context, u user.User) error {
|
||||
}
|
||||
|
||||
func (r *Users) GetByID(ctx context.Context, id uuid.UUID) (user.User, error) {
|
||||
return r.one(ctx, `SELECT `+userColumns+` FROM users WHERE id = $1`, id)
|
||||
return r.one(ctx, `SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1`, id)
|
||||
}
|
||||
|
||||
func (r *Users) GetByUsername(ctx context.Context, username string) (user.User, error) {
|
||||
return r.one(ctx, `SELECT `+userColumns+` FROM users WHERE username = $1`, username)
|
||||
return r.one(ctx, `SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1`, username)
|
||||
}
|
||||
|
||||
func (r *Users) ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
|
||||
@@ -72,6 +70,5 @@ func (r *Users) one(ctx context.Context, query string, arg any) (user.User, erro
|
||||
if err != nil {
|
||||
return user.User{}, fmt.Errorf("select user: %w", postgres.Classify(err))
|
||||
}
|
||||
u.CreatedAt = u.CreatedAt.UTC()
|
||||
return u, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user