feat(message): store messages in Postgres

This commit is contained in:
kk10
2026-10-05 13:26:21 +03:00
parent 04f7c046b6
commit 385a8c0312
6 changed files with 82 additions and 36 deletions
+1 -3
View File
@@ -15,7 +15,6 @@ import (
"mtusi2026-messenger/internal/logger"
"mtusi2026-messenger/internal/postgres"
"mtusi2026-messenger/internal/service"
"mtusi2026-messenger/internal/store"
)
func Run() error {
@@ -41,12 +40,11 @@ func Run() error {
defer pool.Close()
queries := db.New(pool)
memory := store.New()
authService := service.NewAuthService(queries, cfg.Server.SessionTTL)
userService := service.NewUserService(queries)
chatService := service.NewChatService(pool, queries)
messageService := service.NewMessageService(memory)
messageService := service.NewMessageService(queries)
router := NewRouter(
log,
+3 -2
View File
@@ -27,8 +27,9 @@ type MessagePageResponse struct {
}
func (r CreateMessageRequest) Validate() bool {
textLen := utf8.RuneCountInString(r.Text)
if strings.TrimSpace(r.Text) == "" || textLen > 4000 {
if strings.TrimSpace(r.Text) == "" ||
strings.ContainsRune(r.Text, 0) ||
utf8.RuneCountInString(r.Text) > 4000 {
return false
}
+2 -2
View File
@@ -53,7 +53,7 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
return
}
message, err := h.service.Create(userID, chatID, req.Text)
message, err := h.service.Create(r.Context(), userID, chatID, req.Text)
switch {
case errors.Is(err, service.ErrMessageChatNotFound):
httpx.WriteError(
@@ -93,7 +93,7 @@ func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) {
return
}
messages, nextCursor, err := h.service.List(userID, chatID, limit, cursor)
messages, nextCursor, err := h.service.List(r.Context(), userID, chatID, limit, cursor)
switch {
case errors.Is(err, service.ErrMessageChatNotFound):
httpx.WriteError(
+2 -2
View File
@@ -24,8 +24,8 @@ var (
)
type chatQueries interface {
CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error)
AddChatMembers(ctx context.Context, arg db.AddChatMembersParams) error
CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error)
GetChat(ctx context.Context, arg db.GetChatParams) (db.GetChatRow, error)
ListChats(ctx context.Context, arg db.ListChatsParams) ([]db.ListChatsRow, error)
}
@@ -143,7 +143,7 @@ func (s *ChatService) List(
var afterID *uuid.UUID
if cursor != nil {
decoded, err := decodeCursor(*cursor)
decoded, err := decodeCursor(*cursor, uuid.Nil)
if err != nil {
return nil, nil, ErrInvalidCursor
}
+3 -2
View File
@@ -12,6 +12,7 @@ import (
var ErrInvalidCursor = errors.New("invalid cursor")
type Cursor struct {
ChatID uuid.UUID `json:"chat_id"`
CreatedAt time.Time `json:"created_at"`
ID uuid.UUID `json:"id"`
}
@@ -21,7 +22,7 @@ func encodeCursor(cursor Cursor) string {
return base64.RawURLEncoding.EncodeToString(data)
}
func decodeCursor(raw string) (Cursor, error) {
func decodeCursor(raw string, chatID uuid.UUID) (Cursor, error) {
data, err := base64.RawURLEncoding.DecodeString(raw)
if err != nil {
return Cursor{}, ErrInvalidCursor
@@ -32,7 +33,7 @@ func decodeCursor(raw string) (Cursor, error) {
return Cursor{}, ErrInvalidCursor
}
if cursor.ID == uuid.Nil || cursor.CreatedAt.IsZero() {
if cursor.ID == uuid.Nil || cursor.CreatedAt.IsZero() || cursor.ChatID != chatID {
return Cursor{}, ErrInvalidCursor
}
+71 -25
View File
@@ -1,52 +1,89 @@
package service
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"mtusi2026-messenger/internal/db"
"mtusi2026-messenger/internal/model"
"mtusi2026-messenger/internal/store"
"mtusi2026-messenger/internal/postgres"
)
var ErrMessageChatNotFound = errors.New("chat not found")
type MessageService struct {
store *store.Memory
type messageQueries interface {
CreateMessage(ctx context.Context, arg db.CreateMessageParams) (db.Message, error)
IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error)
ListMessages(ctx context.Context, arg db.ListMessagesParams) ([]db.Message, error)
}
func NewMessageService(store *store.Memory) *MessageService {
return &MessageService{store: store}
type MessageService struct {
q messageQueries
}
func NewMessageService(q *db.Queries) *MessageService {
return &MessageService{q: q}
}
func (s *MessageService) Create(
ctx context.Context,
userID uuid.UUID,
chatID uuid.UUID,
text string,
) (model.Message, error) {
message, err := s.store.CreateMessage(chatID, userID, text)
if errors.Is(err, store.ErrNotFound) {
id, err := uuid.NewV7()
if err != nil {
return model.Message{}, err
}
row, err := s.q.CreateMessage(ctx, db.CreateMessageParams{
ID: id,
ChatID: chatID,
SenderID: userID,
Text: text,
})
if postgres.IsNotFound(err) {
return model.Message{}, ErrMessageChatNotFound
}
if err != nil {
return model.Message{}, err
}
return message, nil
return model.Message{
ID: row.ID,
ChatID: row.ChatID,
SenderID: row.SenderID,
Text: row.Text,
CreatedAt: row.CreatedAt,
}, nil
}
func (s *MessageService) List(
ctx context.Context,
userID uuid.UUID,
chatID uuid.UUID,
limit int,
cursor *string,
) ([]model.Message, *string, error) {
isMember, err := s.q.IsChatMember(ctx, db.IsChatMemberParams{
ChatID: chatID,
UserID: userID,
})
if err != nil {
return nil, nil, err
}
if !isMember {
return nil, nil, ErrMessageChatNotFound
}
var afterCreatedAt *time.Time
var afterID *uuid.UUID
if cursor != nil {
decoded, err := decodeCursor(*cursor)
decoded, err := decodeCursor(*cursor, chatID)
if err != nil {
return nil, nil, ErrInvalidCursor
}
@@ -55,28 +92,37 @@ func (s *MessageService) List(
afterID = &decoded.ID
}
messages, hasMore, err := s.store.ListMessages(
chatID,
userID,
afterCreatedAt,
afterID,
limit,
)
if errors.Is(err, store.ErrNotFound) {
return nil, nil, ErrMessageChatNotFound
}
if errors.Is(err, store.ErrInvalidCursor) {
return nil, nil, ErrInvalidCursor
}
rows, err := s.q.ListMessages(ctx, db.ListMessagesParams{
ChatID: chatID,
AfterCreatedAt: afterCreatedAt,
AfterID: afterID,
Lim: int32(limit + 1),
})
if err != nil {
return nil, nil, err
}
var next *string
if hasMore && len(messages) > 0 {
last := messages[len(messages)-1]
hasMore := len(rows) > limit
if hasMore {
rows = rows[:limit]
}
messages := make([]model.Message, 0, len(rows))
for _, r := range rows {
messages = append(messages, model.Message{
ID: r.ID,
ChatID: r.ChatID,
SenderID: r.SenderID,
Text: r.Text,
CreatedAt: r.CreatedAt,
})
}
var next *string
if hasMore {
last := messages[len(messages)-1]
c := encodeCursor(Cursor{
ChatID: chatID,
CreatedAt: last.CreatedAt,
ID: last.ID,
})