11 changed files with 234 additions and 114 deletions
+1 -1
View File
@@ -57,7 +57,7 @@ docker compose down -v
## Архитектура и решения ## Архитектура и решения
Процессы/хранилища: `api` (Go), `postgres`, `redis`, одноразовый `migrate` (goose). Источник истины - PostgreSQL. Redis хранит только кэш сессий: TTL записи = min(60 с, `SESSION_TTL_SECONDS`); при logout запись удаляется сначала из PostgreSQL, затем из Redis. При недоступности Redis API обходит кэш и читает сессию из PostgreSQL; при недоступности PostgreSQL API отвечает `503`. Создание чата выполняется в одной транзакции (откат проверяется `TestCreateChatRollback`). Процессы/хранилища: `api` (Go), `postgres`, `redis`, одноразовый `migrate` (goose). Источник истины - PostgreSQL. Redis хранит только кэш сессий: TTL записи = min(60 с, оставшийся срок сессии до `expires_at`); при logout запись удаляется сначала из PostgreSQL, затем из Redis. При недоступности Redis API обходит кэш и читает сессию из PostgreSQL; при недоступности PostgreSQL API отвечает `503`. Создание чата выполняется в одной транзакции (откат проверяется `TestCreateChatRollback`).
Пароли хешируются bcrypt; перед этим пароль проходит через SHA-256, чтобы обойти ограничение bcrypt в 72 байта. Пароли хешируются bcrypt; перед этим пароль проходит через SHA-256, чтобы обойти ограничение bcrypt в 72 байта.
+18 -7
View File
@@ -40,7 +40,7 @@ WHERE c.id = sqlc.arg(id)
AND m.user_id = sqlc.arg(user_id) AND m.user_id = sqlc.arg(user_id)
); );
-- name: ListChats :many -- name: ListChatsFirstPage :many
SELECT SELECT
c.*, c.*,
ARRAY( ARRAY(
@@ -51,12 +51,23 @@ SELECT
FROM chats c FROM chats c
JOIN chat_members m ON m.chat_id = c.id JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = sqlc.arg(user_id) WHERE m.user_id = sqlc.arg(user_id)
AND ( ORDER BY c.created_at, c.id
sqlc.narg(after_created_at)::timestamptz IS NULL LIMIT sqlc.arg(lim);
OR (c.created_at, c.id) > (
sqlc.narg(after_created_at)::timestamptz, -- name: ListChatsAfter :many
sqlc.narg(after_id)::uuid SELECT
) c.*,
ARRAY(
SELECT cm.user_id FROM chat_members cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = sqlc.arg(user_id)
AND (c.created_at, c.id) > (
sqlc.arg(after_created_at)::timestamptz,
sqlc.arg(after_id)::uuid
) )
ORDER BY c.created_at, c.id ORDER BY c.created_at, c.id
LIMIT sqlc.arg(lim); LIMIT sqlc.arg(lim);
+10 -7
View File
@@ -17,15 +17,18 @@ WHERE EXISTS (
) )
RETURNING *; RETURNING *;
-- name: ListMessages :many -- name: ListMessagesFirstPage :many
SELECT * FROM messages SELECT * FROM messages
WHERE chat_id = sqlc.arg(chat_id) WHERE chat_id = sqlc.arg(chat_id)
AND ( ORDER BY created_at, id
sqlc.narg(after_created_at)::timestamptz IS NULL LIMIT sqlc.arg(lim);
OR (created_at, id) > (
sqlc.narg(after_created_at)::timestamptz, -- name: ListMessagesAfter :many
sqlc.narg(after_id)::uuid SELECT * FROM messages
) WHERE chat_id = sqlc.arg(chat_id)
AND (created_at, id) > (
sqlc.arg(after_created_at)::timestamptz,
sqlc.arg(after_id)::uuid
) )
ORDER BY created_at, id ORDER BY created_at, id
LIMIT sqlc.arg(lim); LIMIT sqlc.arg(lim);
+2 -2
View File
@@ -9,8 +9,8 @@ INSERT INTO sessions (
sqlc.arg(expires_at) sqlc.arg(expires_at)
); );
-- name: GetSessionUserID :one -- name: GetActiveSession :one
SELECT user_id FROM sessions SELECT user_id, expires_at FROM sessions
WHERE token_hash = sqlc.arg(token_hash) WHERE token_hash = sqlc.arg(token_hash)
AND expires_at > now(); AND expires_at > now();
+64 -15
View File
@@ -116,7 +116,7 @@ func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (boo
return exists, err return exists, err
} }
const listChats = `-- name: ListChats :many const listChatsAfter = `-- name: ListChatsAfter :many
SELECT SELECT
c.id, c.title, c.created_at, c.id, c.title, c.created_at,
ARRAY( ARRAY(
@@ -127,33 +127,30 @@ SELECT
FROM chats c FROM chats c
JOIN chat_members m ON m.chat_id = c.id JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = $1 WHERE m.user_id = $1
AND ( AND (c.created_at, c.id) > (
$2::timestamptz IS NULL $2::timestamptz,
OR (c.created_at, c.id) > ( $3::uuid
$2::timestamptz,
$3::uuid
)
) )
ORDER BY c.created_at, c.id ORDER BY c.created_at, c.id
LIMIT $4 LIMIT $4
` `
type ListChatsParams struct { type ListChatsAfterParams struct {
UserID uuid.UUID UserID uuid.UUID
AfterCreatedAt *time.Time AfterCreatedAt time.Time
AfterID *uuid.UUID AfterID uuid.UUID
Lim int32 Lim int32
} }
type ListChatsRow struct { type ListChatsAfterRow struct {
ID uuid.UUID ID uuid.UUID
Title string Title string
CreatedAt time.Time CreatedAt time.Time
MemberIds []uuid.UUID MemberIds []uuid.UUID
} }
func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) { func (q *Queries) ListChatsAfter(ctx context.Context, arg ListChatsAfterParams) ([]ListChatsAfterRow, error) {
rows, err := q.db.Query(ctx, listChats, rows, err := q.db.Query(ctx, listChatsAfter,
arg.UserID, arg.UserID,
arg.AfterCreatedAt, arg.AfterCreatedAt,
arg.AfterID, arg.AfterID,
@@ -163,9 +160,61 @@ func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListCha
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close()
items := []ListChatsRow{} items := []ListChatsAfterRow{}
for rows.Next() { for rows.Next() {
var i ListChatsRow var i ListChatsAfterRow
if err := rows.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.MemberIds,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listChatsFirstPage = `-- name: ListChatsFirstPage :many
SELECT
c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id FROM chat_members cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = $1
ORDER BY c.created_at, c.id
LIMIT $2
`
type ListChatsFirstPageParams struct {
UserID uuid.UUID
Lim int32
}
type ListChatsFirstPageRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) ListChatsFirstPage(ctx context.Context, arg ListChatsFirstPageParams) ([]ListChatsFirstPageRow, error) {
rows, err := q.db.Query(ctx, listChatsFirstPage, arg.UserID, arg.Lim)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListChatsFirstPageRow{}
for rows.Next() {
var i ListChatsFirstPageRow
if err := rows.Scan( if err := rows.Scan(
&i.ID, &i.ID,
&i.Title, &i.Title,
+47 -12
View File
@@ -57,29 +57,26 @@ func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (M
return i, err return i, err
} }
const listMessages = `-- name: ListMessages :many const listMessagesAfter = `-- name: ListMessagesAfter :many
SELECT id, chat_id, sender_id, text, created_at FROM messages SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = $1 WHERE chat_id = $1
AND ( AND (created_at, id) > (
$2::timestamptz IS NULL $2::timestamptz,
OR (created_at, id) > ( $3::uuid
$2::timestamptz,
$3::uuid
)
) )
ORDER BY created_at, id ORDER BY created_at, id
LIMIT $4 LIMIT $4
` `
type ListMessagesParams struct { type ListMessagesAfterParams struct {
ChatID uuid.UUID ChatID uuid.UUID
AfterCreatedAt *time.Time AfterCreatedAt time.Time
AfterID *uuid.UUID AfterID uuid.UUID
Lim int32 Lim int32
} }
func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]Message, error) { func (q *Queries) ListMessagesAfter(ctx context.Context, arg ListMessagesAfterParams) ([]Message, error) {
rows, err := q.db.Query(ctx, listMessages, rows, err := q.db.Query(ctx, listMessagesAfter,
arg.ChatID, arg.ChatID,
arg.AfterCreatedAt, arg.AfterCreatedAt,
arg.AfterID, arg.AfterID,
@@ -108,3 +105,41 @@ func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]M
} }
return items, nil return items, nil
} }
const listMessagesFirstPage = `-- name: ListMessagesFirstPage :many
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = $1
ORDER BY created_at, id
LIMIT $2
`
type ListMessagesFirstPageParams struct {
ChatID uuid.UUID
Lim int32
}
func (q *Queries) ListMessagesFirstPage(ctx context.Context, arg ListMessagesFirstPageParams) ([]Message, error) {
rows, err := q.db.Query(ctx, listMessagesFirstPage, arg.ChatID, arg.Lim)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Message{}
for rows.Next() {
var i Message
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
+12 -7
View File
@@ -62,15 +62,20 @@ func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) (int64, e
return result.RowsAffected(), nil return result.RowsAffected(), nil
} }
const getSessionUserID = `-- name: GetSessionUserID :one const getActiveSession = `-- name: GetActiveSession :one
SELECT user_id FROM sessions SELECT user_id, expires_at FROM sessions
WHERE token_hash = $1 WHERE token_hash = $1
AND expires_at > now() AND expires_at > now()
` `
func (q *Queries) GetSessionUserID(ctx context.Context, tokenHash string) (uuid.UUID, error) { type GetActiveSessionRow struct {
row := q.db.QueryRow(ctx, getSessionUserID, tokenHash) UserID uuid.UUID
var user_id uuid.UUID ExpiresAt time.Time
err := row.Scan(&user_id) }
return user_id, err
func (q *Queries) GetActiveSession(ctx context.Context, tokenHash string) (GetActiveSessionRow, error) {
row := q.db.QueryRow(ctx, getActiveSession, tokenHash)
var i GetActiveSessionRow
err := row.Scan(&i.UserID, &i.ExpiresAt)
return i, err
} }
+7
View File
@@ -2,6 +2,8 @@ package httpx
import ( import (
"encoding/json" "encoding/json"
"errors"
"io"
"mime" "mime"
"net/http" "net/http"
@@ -25,5 +27,10 @@ func DecodeJSONBody(w http.ResponseWriter, r *http.Request, requestID string, ds
return false return false
} }
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid request body", requestID)
return false
}
return true return true
} }
+10 -14
View File
@@ -26,7 +26,7 @@ var (
type authQueries interface { type authQueries interface {
CreateSession(ctx context.Context, arg db.CreateSessionParams) error CreateSession(ctx context.Context, arg db.CreateSessionParams) error
DeleteSession(ctx context.Context, tokenHash string) (int64, error) DeleteSession(ctx context.Context, tokenHash string) (int64, error)
GetSessionUserID(ctx context.Context, tokenHash string) (uuid.UUID, error) GetActiveSession(ctx context.Context, tokenHash string) (db.GetActiveSessionRow, error)
GetUserByUsername(ctx context.Context, username string) (db.User, error) GetUserByUsername(ctx context.Context, username string) (db.User, error)
} }
@@ -107,7 +107,7 @@ func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID
s.log.Warn("session cache get failed, falling back to database", "error", err) s.log.Warn("session cache get failed, falling back to database", "error", err)
} }
userID, err := s.q.GetSessionUserID(ctx, tokenHash) row, err := s.q.GetActiveSession(ctx, tokenHash)
if postgres.IsNotFound(err) { if postgres.IsNotFound(err) {
return uuid.Nil, ErrUnauthorized return uuid.Nil, ErrUnauthorized
} }
@@ -115,13 +115,16 @@ func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID
return uuid.Nil, err return uuid.Nil, err
} }
cctx, cancel = context.WithTimeout(ctx, cacheOpTimeout) ttl := min(time.Until(row.ExpiresAt), sessionCacheTTL)
if err := s.cache.Set(cctx, key, userID.String(), s.cacheTTL()).Err(); err != nil { if ttl > 0 {
s.log.Warn("session cache set failed", "error", err) cctx, cancel = context.WithTimeout(ctx, cacheOpTimeout)
if err := s.cache.Set(cctx, key, row.UserID.String(), ttl).Err(); err != nil {
s.log.Warn("session cache set failed", "error", err)
}
cancel()
} }
cancel()
return userID, nil return row.UserID, nil
} }
func (s *AuthService) Logout(ctx context.Context, token string) error { func (s *AuthService) Logout(ctx context.Context, token string) error {
@@ -147,10 +150,3 @@ func (s *AuthService) Logout(ctx context.Context, token string) error {
func cacheKey(tokenHash string) string { func cacheKey(tokenHash string) string {
return "session:" + tokenHash return "session:" + tokenHash
} }
func (s *AuthService) cacheTTL() time.Duration {
if s.sessionTTL < sessionCacheTTL {
return s.sessionTTL
}
return sessionCacheTTL
}
+46 -33
View File
@@ -5,7 +5,6 @@ import (
"context" "context"
"errors" "errors"
"slices" "slices"
"time"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
@@ -27,7 +26,8 @@ type chatQueries interface {
AddChatMembers(ctx context.Context, arg db.AddChatMembersParams) error AddChatMembers(ctx context.Context, arg db.AddChatMembersParams) error
CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error) CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error)
GetChat(ctx context.Context, arg db.GetChatParams) (db.GetChatRow, error) GetChat(ctx context.Context, arg db.GetChatParams) (db.GetChatRow, error)
ListChats(ctx context.Context, arg db.ListChatsParams) ([]db.ListChatsRow, error) ListChatsAfter(ctx context.Context, arg db.ListChatsAfterParams) ([]db.ListChatsAfterRow, error)
ListChatsFirstPage(ctx context.Context, arg db.ListChatsFirstPageParams) ([]db.ListChatsFirstPageRow, error)
} }
type txBeginner interface { type txBeginner interface {
@@ -142,48 +142,61 @@ func (s *ChatService) List(
limit int, limit int,
cursor *string, cursor *string,
) ([]model.Chat, *string, error) { ) ([]model.Chat, *string, error) {
var afterCreatedAt *time.Time var chats []model.Chat
var afterID *uuid.UUID
if cursor != nil { if cursor == nil {
decoded, err := decodeCursor(*cursor, uuid.Nil) rows, err := s.q.ListChatsFirstPage(ctx, db.ListChatsFirstPageParams{
UserID: userID,
Lim: int32(limit + 1),
})
if err != nil { if err != nil {
return nil, nil, err
}
chats = make([]model.Chat, 0, len(rows))
for _, r := range rows {
chats = append(chats, model.Chat{
ID: r.ID,
Title: r.Title,
CreatedAt: r.CreatedAt,
MemberIDs: r.MemberIds,
})
}
} else {
decoded, derr := decodeCursor(*cursor, uuid.Nil)
if derr != nil {
return nil, nil, ErrInvalidCursor return nil, nil, ErrInvalidCursor
} }
afterCreatedAt = &decoded.CreatedAt rows, err := s.q.ListChatsAfter(ctx, db.ListChatsAfterParams{
afterID = &decoded.ID UserID: userID,
} AfterCreatedAt: decoded.CreatedAt,
AfterID: decoded.ID,
rows, err := s.q.ListChats(ctx, db.ListChatsParams{ Lim: int32(limit + 1),
UserID: userID,
AfterCreatedAt: afterCreatedAt,
AfterID: afterID,
Lim: int32(limit + 1),
})
if err != nil {
return nil, nil, err
}
hasMore := len(rows) > limit
if hasMore {
rows = rows[:limit]
}
chats := make([]model.Chat, 0, len(rows))
for _, r := range rows {
chats = append(chats, model.Chat{
ID: r.ID,
Title: r.Title,
CreatedAt: r.CreatedAt,
MemberIDs: r.MemberIds,
}) })
if err != nil {
return nil, nil, err
}
chats = make([]model.Chat, 0, len(rows))
for _, r := range rows {
chats = append(chats, model.Chat{
ID: r.ID,
Title: r.Title,
CreatedAt: r.CreatedAt,
MemberIDs: r.MemberIds,
})
}
}
hasMore := len(chats) > limit
if hasMore {
chats = chats[:limit]
} }
var next *string var next *string
if hasMore { if hasMore {
last := chats[len(chats)-1] last := chats[len(chats)-1]
c := encodeCursor(Cursor{ c := encodeCursor(Cursor{
CreatedAt: last.CreatedAt, CreatedAt: last.CreatedAt,
ID: last.ID, ID: last.ID,
+17 -16
View File
@@ -3,7 +3,6 @@ package service
import ( import (
"context" "context"
"errors" "errors"
"time"
"github.com/google/uuid" "github.com/google/uuid"
@@ -17,7 +16,8 @@ var ErrMessageChatNotFound = errors.New("chat not found")
type messageQueries interface { type messageQueries interface {
CreateMessage(ctx context.Context, arg db.CreateMessageParams) (db.Message, error) CreateMessage(ctx context.Context, arg db.CreateMessageParams) (db.Message, error)
IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error) IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error)
ListMessages(ctx context.Context, arg db.ListMessagesParams) ([]db.Message, error) ListMessagesAfter(ctx context.Context, arg db.ListMessagesAfterParams) ([]db.Message, error)
ListMessagesFirstPage(ctx context.Context, arg db.ListMessagesFirstPageParams) ([]db.Message, error)
} }
type MessageService struct { type MessageService struct {
@@ -79,25 +79,26 @@ func (s *MessageService) List(
return nil, nil, ErrMessageChatNotFound return nil, nil, ErrMessageChatNotFound
} }
var afterCreatedAt *time.Time var rows []db.Message
var afterID *uuid.UUID
if cursor != nil { if cursor == nil {
decoded, err := decodeCursor(*cursor, chatID) rows, err = s.q.ListMessagesFirstPage(ctx, db.ListMessagesFirstPageParams{
if err != nil { ChatID: chatID,
Lim: int32(limit + 1),
})
} else {
decoded, derr := decodeCursor(*cursor, chatID)
if derr != nil {
return nil, nil, ErrInvalidCursor return nil, nil, ErrInvalidCursor
} }
afterCreatedAt = &decoded.CreatedAt rows, err = s.q.ListMessagesAfter(ctx, db.ListMessagesAfterParams{
afterID = &decoded.ID ChatID: chatID,
AfterCreatedAt: decoded.CreatedAt,
AfterID: decoded.ID,
Lim: int32(limit + 1),
})
} }
rows, err := s.q.ListMessages(ctx, db.ListMessagesParams{
ChatID: chatID,
AfterCreatedAt: afterCreatedAt,
AfterID: afterID,
Lim: int32(limit + 1),
})
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }