forked from mtusi2026/mtusi2026lab2
Реализация на 4
This commit is contained in:
@@ -1,149 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
const chatCacheName = "CHATS_CACHE"
|
||||
|
||||
type ChatCache interface {
|
||||
Create(ctx context.Context, input dto.CreateChat) (dto.Chat, error)
|
||||
GetForMember(ctx context.Context, chatID, userID uuid.UUID) (dto.Chat, error)
|
||||
ListForMember(ctx context.Context, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Chat], error)
|
||||
}
|
||||
|
||||
type chatCache struct {
|
||||
mu sync.RWMutex
|
||||
store *CopyAndWriteCache[uuid.UUID, dto.Chat]
|
||||
users UserCache
|
||||
}
|
||||
|
||||
func NewChatCache(users UserCache) ChatCache {
|
||||
if users == nil {
|
||||
panic("chat cache requires a user repository")
|
||||
}
|
||||
return &chatCache{
|
||||
store: NewCopyAndWriteCache[uuid.UUID, dto.Chat](chatCacheName),
|
||||
users: users,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *chatCache) Create(ctx context.Context, input dto.CreateChat) (dto.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Chat{}, err
|
||||
}
|
||||
if strings.TrimSpace(input.Title) == "" || utf8.RuneCountInString(input.Title) > 100 ||
|
||||
len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "invalid chat fields")
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(input.MemberIDs))
|
||||
for _, memberID := range input.MemberIDs {
|
||||
if memberID == uuid.Nil {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "invalid chat member")
|
||||
}
|
||||
if _, duplicate := seen[memberID]; duplicate {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "duplicate chat member")
|
||||
}
|
||||
seen[memberID] = struct{}{}
|
||||
if _, err := c.users.GetByID(ctx, memberID); err != nil {
|
||||
if appErr, ok := apperr.As(err); ok && appErr.Code() == apperr.CodeNotFound {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "unknown chat member")
|
||||
}
|
||||
return dto.Chat{}, err
|
||||
}
|
||||
}
|
||||
if _, included := seen[input.CreatorID]; !included {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "creator must be a chat member")
|
||||
}
|
||||
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return dto.Chat{}, apperr.Wrap(err, apperr.CodeInternalError, "generate chat ID")
|
||||
}
|
||||
chat := dto.Chat{
|
||||
ID: id,
|
||||
Title: input.Title,
|
||||
MemberIDs: append([]uuid.UUID(nil), input.MemberIDs...),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if !c.store.Store(chat.ID, chat) {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInternalError, "store chat")
|
||||
}
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (c *chatCache) GetForMember(ctx context.Context, chatID, userID uuid.UUID) (dto.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Chat{}, err
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
chat, ok := c.store.Get(chatID)
|
||||
if !ok || !slices.Contains(chat.MemberIDs, userID) {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (c *chatCache) ListForMember(ctx context.Context, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Chat], error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Page[dto.Chat]{}, err
|
||||
}
|
||||
pageSize, err := pageLimit(limit)
|
||||
if err != nil {
|
||||
return dto.Page[dto.Chat]{}, err
|
||||
}
|
||||
|
||||
c.mu.RLock()
|
||||
all := c.store.GetList()
|
||||
chats := make([]dto.Chat, 0, len(all))
|
||||
for _, chat := range all {
|
||||
if slices.Contains(chat.MemberIDs, userID) {
|
||||
chats = append(chats, cloneChat(chat))
|
||||
}
|
||||
}
|
||||
c.mu.RUnlock()
|
||||
|
||||
sort.Slice(chats, func(i, j int) bool {
|
||||
return lessKey(chats[i].CreatedAt, chats[i].ID, chats[j].CreatedAt, chats[j].ID)
|
||||
})
|
||||
start := 0
|
||||
if afterID != nil {
|
||||
start = -1
|
||||
for i, chat := range chats {
|
||||
if chat.ID == *afterID {
|
||||
start = i + 1
|
||||
break
|
||||
}
|
||||
}
|
||||
if start < 0 {
|
||||
return dto.Page[dto.Chat]{}, apperr.New(apperr.CodeInvalidRequest, "invalid cursor")
|
||||
}
|
||||
}
|
||||
end := min(start+pageSize, len(chats))
|
||||
page := dto.Page[dto.Chat]{Items: chats[start:end]}
|
||||
if end < len(chats) {
|
||||
id := chats[end-1].ID
|
||||
page.NextCursorID = &id
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func cloneChat(chat dto.Chat) dto.Chat {
|
||||
chat.MemberIDs = append([]uuid.UUID(nil), chat.MemberIDs...)
|
||||
return chat
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
const MessageCacheName = "MESSAGE_CACHE"
|
||||
|
||||
type MessageCache interface {
|
||||
Create(ctx context.Context, input dto.CreateMessage) (dto.Message, error)
|
||||
ListForChat(ctx context.Context, chatID, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Message], error)
|
||||
}
|
||||
|
||||
type messageCache struct {
|
||||
mu sync.RWMutex
|
||||
store *CopyAndWriteCache[uuid.UUID, dto.Message]
|
||||
byChat map[uuid.UUID][]dto.Message
|
||||
chats ChatCache
|
||||
}
|
||||
|
||||
func NewMessageCache(chats ChatCache) MessageCache {
|
||||
if chats == nil {
|
||||
panic("message cache requires a chat repository")
|
||||
}
|
||||
return &messageCache{
|
||||
store: NewCopyAndWriteCache[uuid.UUID, dto.Message](MessageCacheName),
|
||||
byChat: make(map[uuid.UUID][]dto.Message),
|
||||
chats: chats,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *messageCache) Create(ctx context.Context, input dto.CreateMessage) (dto.Message, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Message{}, err
|
||||
}
|
||||
if _, err := c.chats.GetForMember(ctx, input.ChatID, input.SenderID); err != nil {
|
||||
return dto.Message{}, err
|
||||
}
|
||||
if strings.TrimSpace(input.Text) == "" || utf8.RuneCountInString(input.Text) > 4000 {
|
||||
return dto.Message{}, apperr.New(apperr.CodeInvalidRequest, "invalid message text")
|
||||
}
|
||||
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return dto.Message{}, apperr.Wrap(err, apperr.CodeInternalError, "generate message ID")
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
message := dto.Message{
|
||||
ID: id,
|
||||
ChatID: input.ChatID,
|
||||
SenderID: input.SenderID,
|
||||
Text: input.Text,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if !c.store.Store(message.ID, message) {
|
||||
return dto.Message{}, apperr.New(apperr.CodeInternalError, "store message")
|
||||
}
|
||||
messages := c.byChat[message.ChatID]
|
||||
index := sort.Search(len(messages), func(i int) bool {
|
||||
return !lessKey(messages[i].CreatedAt, messages[i].ID, message.CreatedAt, message.ID)
|
||||
})
|
||||
messages = append(messages, dto.Message{})
|
||||
copy(messages[index+1:], messages[index:])
|
||||
messages[index] = message
|
||||
c.byChat[message.ChatID] = messages
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (c *messageCache) ListForChat(ctx context.Context, chatID, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Message], error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Page[dto.Message]{}, err
|
||||
}
|
||||
if _, err := c.chats.GetForMember(ctx, chatID, userID); err != nil {
|
||||
return dto.Page[dto.Message]{}, err
|
||||
}
|
||||
pageSize, err := pageLimit(limit)
|
||||
if err != nil {
|
||||
return dto.Page[dto.Message]{}, err
|
||||
}
|
||||
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
messages := c.byChat[chatID]
|
||||
start := 0
|
||||
if afterID != nil {
|
||||
cursor, ok := c.store.Get(*afterID)
|
||||
if !ok || cursor.ChatID != chatID {
|
||||
return dto.Page[dto.Message]{}, apperr.New(apperr.CodeInvalidRequest, "invalid cursor")
|
||||
}
|
||||
start = sort.Search(len(messages), func(i int) bool {
|
||||
return lessKey(cursor.CreatedAt, cursor.ID, messages[i].CreatedAt, messages[i].ID)
|
||||
})
|
||||
}
|
||||
end := min(start+pageSize, len(messages))
|
||||
items := make([]dto.Message, end-start)
|
||||
copy(items, messages[start:end])
|
||||
page := dto.Page[dto.Message]{Items: items}
|
||||
if end < len(messages) {
|
||||
id := messages[end-1].ID
|
||||
page.NextCursorID = &id
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
func pageLimit(rawLimit *int) (int, error) {
|
||||
limit := 50
|
||||
if rawLimit != nil {
|
||||
limit = *rawLimit
|
||||
}
|
||||
if limit < 1 || limit > 100 {
|
||||
return 0, apperr.New(apperr.CodeInvalidRequest, "invalid limit")
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
func lessKey(leftTime time.Time, leftID uuid.UUID, rightTime time.Time, rightID uuid.UUID) bool {
|
||||
if !leftTime.Equal(rightTime) {
|
||||
return leftTime.Before(rightTime)
|
||||
}
|
||||
return bytes.Compare(leftID[:], rightID[:]) < 0
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
const UserCacheName = "USERS_CACHE"
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type UserCache interface {
|
||||
Create(ctx context.Context, input dto.CreateUser) (dto.User, error)
|
||||
GetByID(ctx context.Context, id uuid.UUID) (dto.User, error)
|
||||
GetByUsername(ctx context.Context, username string) (dto.User, error)
|
||||
}
|
||||
|
||||
type userCache struct {
|
||||
mu sync.RWMutex
|
||||
store *CopyAndWriteCache[uuid.UUID, dto.User]
|
||||
byUsername map[string]uuid.UUID
|
||||
}
|
||||
|
||||
func NewUserCache() UserCache {
|
||||
return &userCache{
|
||||
store: NewCopyAndWriteCache[uuid.UUID, dto.User](UserCacheName),
|
||||
byUsername: make(map[string]uuid.UUID),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *userCache) Create(ctx context.Context, input dto.CreateUser) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
if !usernamePattern.MatchString(input.Username) ||
|
||||
strings.TrimSpace(input.DisplayName) == "" ||
|
||||
utf8.RuneCountInString(input.DisplayName) > 100 {
|
||||
return dto.User{}, apperr.New(apperr.CodeInvalidRequest, "invalid user fields")
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if _, exists := c.byUsername[input.Username]; exists {
|
||||
return dto.User{}, apperr.New(apperr.CodeConflict, "username already exists")
|
||||
}
|
||||
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return dto.User{}, apperr.Wrap(err, apperr.CodeInternalError, "generate user ID")
|
||||
}
|
||||
user := dto.User{
|
||||
ID: id,
|
||||
Username: input.Username,
|
||||
DisplayName: input.DisplayName,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if !c.store.Store(user.ID, user) {
|
||||
return dto.User{}, apperr.New(apperr.CodeInternalError, "store user")
|
||||
}
|
||||
c.byUsername[user.Username] = user.ID
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (c *userCache) GetByID(ctx context.Context, id uuid.UUID) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
user, ok := c.store.Get(id)
|
||||
if !ok {
|
||||
return dto.User{}, apperr.New(apperr.CodeNotFound, "user not found")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (c *userCache) GetByUsername(ctx context.Context, username string) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
id, ok := c.byUsername[username]
|
||||
if !ok {
|
||||
return dto.User{}, apperr.New(apperr.CodeNotFound, "user not found")
|
||||
}
|
||||
user, ok := c.store.Get(id)
|
||||
if !ok {
|
||||
return dto.User{}, apperr.New(apperr.CodeInternalError, "user index is inconsistent")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
type ChatsRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatsRepo(pool *pgxpool.Pool) *ChatsRepo {
|
||||
return &ChatsRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *ChatsRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.Chat) error {
|
||||
const insertChat = `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`
|
||||
if _, err := tx.Exec(ctx, insertChat, req.ID, req.Title, req.CreatedAt); err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to create chat")
|
||||
}
|
||||
const insertMembers = `INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT $1, user_id FROM unnest($2::uuid[]) AS members(user_id)`
|
||||
if _, err := tx.Exec(ctx, insertMembers, req.ID, req.MemberIDs); err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
|
||||
pgErr.Code == pgerrcode.ForeignKeyViolation && pgErr.ConstraintName == "chat_members_user_fk" {
|
||||
return apperr.Wrap(err, apperr.CodeBadRequest, "unknown chat member")
|
||||
}
|
||||
return apperr.WrapPostgres(err, "failed to create chat members")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ChatsRepo) GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error) {
|
||||
const query = `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 access WHERE access.chat_id = c.id AND access.user_id = $2)`
|
||||
return scanChat(r.pool.QueryRow(ctx, query, req.ChatID, req.UserID))
|
||||
}
|
||||
|
||||
func (r *ChatsRepo) ListForMember(ctx context.Context, userID uuid.UUID, page dto.PageQuery) ([]dto.Chat, error) {
|
||||
query := `WITH page AS MATERIALIZED (
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c JOIN chat_members access ON access.chat_id = c.id
|
||||
WHERE access.user_id = $1`
|
||||
args := []any{userID, page.Limit}
|
||||
if page.After != nil {
|
||||
query += ` AND (c.created_at, c.id) > ($3, $4)`
|
||||
args = append(args, page.After.CreatedAt, page.After.ID)
|
||||
}
|
||||
query += ` ORDER BY c.created_at, c.id LIMIT $2
|
||||
)
|
||||
SELECT p.id, p.title, p.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = p.id ORDER BY m.user_id)
|
||||
FROM page p ORDER BY p.created_at, p.id`
|
||||
rows, err := r.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list chats")
|
||||
}
|
||||
defer rows.Close()
|
||||
chats := make([]dto.Chat, 0)
|
||||
for rows.Next() {
|
||||
chat, err := scanChat(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chats = append(chats, *chat)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list chats")
|
||||
}
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
func scanChat(row pgx.Row) (*dto.Chat, error) {
|
||||
var chat dto.Chat
|
||||
if err := row.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get chat")
|
||||
}
|
||||
return &chat, nil
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
type MessagesRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessagesRepo(pool *pgxpool.Pool) *MessagesRepo {
|
||||
return &MessagesRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) Create(ctx context.Context, req dto.Message) error {
|
||||
const query = `INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`
|
||||
if _, err := r.pool.Exec(ctx, query, req.ID, req.ChatID, req.SenderID, req.Text, req.CreatedAt); err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
|
||||
pgErr.Code == pgerrcode.ForeignKeyViolation && pgErr.ConstraintName == "messages_sender_member_fk" {
|
||||
return apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return apperr.WrapPostgres(err, "failed to create message")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error) {
|
||||
const query = `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 AND id = $2`
|
||||
return scanMessage(r.pool.QueryRow(ctx, query, chatID, messageID))
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error) {
|
||||
query := `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1`
|
||||
args := []any{chatID, page.Limit}
|
||||
if page.After != nil {
|
||||
query += ` AND (created_at, id) > ($3, $4)`
|
||||
args = append(args, page.After.CreatedAt, page.After.ID)
|
||||
}
|
||||
query += ` ORDER BY created_at, id LIMIT $2`
|
||||
rows, err := r.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list messages")
|
||||
}
|
||||
defer rows.Close()
|
||||
messages := make([]dto.Message, 0)
|
||||
for rows.Next() {
|
||||
message, err := scanMessage(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
messages = append(messages, *message)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list messages")
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
func scanMessage(row pgx.Row) (*dto.Message, error) {
|
||||
var message dto.Message
|
||||
if err := row.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get message")
|
||||
}
|
||||
return &message, nil
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
|
||||
)
|
||||
|
||||
type RefreshTokensRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewRefreshTokensRepo(pool *pgxpool.Pool) *RefreshTokensRepo {
|
||||
return &RefreshTokensRepo{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) Create(ctx context.Context, req dto.StoredRefreshToken) error {
|
||||
return r.create(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.StoredRefreshToken) error {
|
||||
return r.create(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByID(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, r.pool, id, false)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByIDTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, tx, id, false)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByIDForUpdate(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, r.pool, id, true)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByIDForUpdateTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, tx, id, true)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) Revoke(ctx context.Context, req dto.RevokeRefreshToken) error {
|
||||
return r.revoke(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) RevokeTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshToken) error {
|
||||
return r.revoke(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) RevokeAllByUserID(ctx context.Context, req dto.RevokeRefreshTokensByUserID) error {
|
||||
return r.revokeAllByUserID(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) RevokeAllByUserIDTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshTokensByUserID) error {
|
||||
return r.revokeAllByUserID(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) DeleteExpired(ctx context.Context) error {
|
||||
const query = `
|
||||
DELETE FROM refresh_tokens
|
||||
WHERE expires_at < $1`
|
||||
|
||||
_, err := r.pool.Exec(ctx, query, time.Now())
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to delete expired refresh tokens")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) create(ctx context.Context, conn postgres.Conn, req dto.StoredRefreshToken) error {
|
||||
const query = `INSERT INTO refresh_tokens (id,
|
||||
user_id,
|
||||
token_hash,
|
||||
user_agent,
|
||||
ip_address,
|
||||
role,
|
||||
expires_at,
|
||||
created_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`
|
||||
|
||||
ct, err := conn.Exec(
|
||||
ctx,
|
||||
query,
|
||||
req.ID,
|
||||
req.UserID,
|
||||
req.TokenHash,
|
||||
req.UserAgent,
|
||||
req.IPAddress,
|
||||
req.Role,
|
||||
req.ExpiresAt,
|
||||
req.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to create refresh token")
|
||||
}
|
||||
|
||||
if ct.RowsAffected() == 0 {
|
||||
return apperr.New(apperr.CodeAlreadyExists, "refresh token already exists")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) getByID(ctx context.Context, conn postgres.Conn, id uuid.UUID, lock bool) (*dto.StoredRefreshToken, error) {
|
||||
const query = `SELECT id,
|
||||
user_id,
|
||||
token_hash,
|
||||
user_agent,
|
||||
ip_address,
|
||||
role,
|
||||
expires_at,
|
||||
revoked_at,
|
||||
created_at
|
||||
FROM refresh_tokens
|
||||
WHERE id = $1`
|
||||
const queryLock = `SELECT id,
|
||||
user_id,
|
||||
token_hash,
|
||||
user_agent,
|
||||
ip_address,
|
||||
role,
|
||||
expires_at,
|
||||
revoked_at,
|
||||
created_at
|
||||
FROM refresh_tokens
|
||||
WHERE id = $1 FOR UPDATE`
|
||||
|
||||
use := query
|
||||
if lock {
|
||||
use = queryLock
|
||||
}
|
||||
|
||||
var token dto.StoredRefreshToken
|
||||
err := conn.QueryRow(ctx, use, id).Scan(
|
||||
&token.ID,
|
||||
&token.UserID,
|
||||
&token.TokenHash,
|
||||
&token.UserAgent,
|
||||
&token.IPAddress,
|
||||
&token.Role,
|
||||
&token.ExpiresAt,
|
||||
&token.RevokedAt,
|
||||
&token.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get refresh by id")
|
||||
}
|
||||
|
||||
return &token, nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) revoke(ctx context.Context, conn postgres.Conn, req dto.RevokeRefreshToken) error {
|
||||
const query = `
|
||||
UPDATE refresh_tokens
|
||||
SET revoked_at = $2
|
||||
WHERE id = $1
|
||||
AND revoked_at IS NULL`
|
||||
|
||||
ct, err := conn.Exec(ctx, query, req.ID, req.RevokedAt)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to revoke refresh token")
|
||||
}
|
||||
|
||||
if ct.RowsAffected() == 0 {
|
||||
return apperr.New(apperr.CodeNotFound, "refresh token not found")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) revokeAllByUserID(ctx context.Context, conn postgres.Conn, req dto.RevokeRefreshTokensByUserID) error {
|
||||
const query = `
|
||||
UPDATE refresh_tokens
|
||||
SET revoked_at = $2
|
||||
WHERE user_id = $1
|
||||
AND revoked_at IS NULL`
|
||||
|
||||
_, err := conn.Exec(ctx, query, req.UserID, req.RevokedAt)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to revoke refresh tokens")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
|
||||
)
|
||||
|
||||
type UsersRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUsersRepo(pool *pgxpool.Pool) *UsersRepo {
|
||||
return &UsersRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *UsersRepo) Create(ctx context.Context, req dto.CreateStoredUser) error {
|
||||
return r.create(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.CreateStoredUser) error {
|
||||
return r.create(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetByID(ctx context.Context, id uuid.UUID) (*dto.User, error) {
|
||||
return r.getByID(ctx, r.pool, id)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetByIDTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.User, error) {
|
||||
return r.getByID(ctx, tx, id)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetByUsername(ctx context.Context, username string) (*dto.User, error) {
|
||||
const query = `SELECT id, username, name, created_at FROM users WHERE username = $1`
|
||||
return scanUser(r.pool.QueryRow(ctx, query, username))
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetCredentialsByUsername(ctx context.Context, username string) (*dto.UserCredentials, error) {
|
||||
const query = `SELECT id, username, name, created_at, password_hash FROM users WHERE username = $1`
|
||||
|
||||
var credentials dto.UserCredentials
|
||||
err := r.pool.QueryRow(ctx, query, username).Scan(
|
||||
&credentials.User.ID,
|
||||
&credentials.User.Username,
|
||||
&credentials.User.DisplayName,
|
||||
&credentials.User.CreatedAt,
|
||||
&credentials.PasswordHash,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get user credentials")
|
||||
}
|
||||
return &credentials, nil
|
||||
}
|
||||
|
||||
func (r *UsersRepo) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
const query = `DELETE FROM users WHERE id = $1`
|
||||
|
||||
ct, err := r.pool.Exec(ctx, query, id)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to delete user")
|
||||
}
|
||||
if ct.RowsAffected() == 0 {
|
||||
return apperr.New(apperr.CodeNotFound, "user not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UsersRepo) create(ctx context.Context, conn postgres.Conn, req dto.CreateStoredUser) error {
|
||||
const query = `INSERT INTO users (id, username, name, password_hash, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)`
|
||||
|
||||
_, err := conn.Exec(ctx, query, req.ID, req.Username, req.DisplayName, req.PasswordHash, req.CreatedAt, req.UpdatedAt)
|
||||
if err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
|
||||
pgErr.Code == pgerrcode.UniqueViolation && pgErr.ConstraintName == "users_username_unique" {
|
||||
return apperr.Wrap(err, apperr.CodeConflict, "username already exists")
|
||||
}
|
||||
return apperr.WrapPostgres(err, "failed to create user")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UsersRepo) getByID(ctx context.Context, conn postgres.Conn, id uuid.UUID) (*dto.User, error) {
|
||||
const query = `SELECT id, username, name, created_at FROM users WHERE id = $1`
|
||||
return scanUser(conn.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func scanUser(row pgx.Row) (*dto.User, error) {
|
||||
var user dto.User
|
||||
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get user")
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
Reference in New Issue
Block a user