358 lines
10 KiB
Go
358 lines
10 KiB
Go
package pgstore
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"mtusi.local/messenger/internal/model"
|
|
)
|
|
|
|
type Store struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func New(pool *pgxpool.Pool) *Store {
|
|
return &Store{pool: pool}
|
|
}
|
|
|
|
func (s *Store) Ping(ctx context.Context) error {
|
|
if err := s.pool.Ping(ctx); err != nil {
|
|
return model.ErrUnavailable
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
|
if !model.ValidUsername(username) || !model.ValidLabel(displayName, 100) || passwordHash == "" {
|
|
return model.User{}, model.ErrInvalid
|
|
}
|
|
id, err := model.NewID()
|
|
if err != nil {
|
|
return model.User{}, err
|
|
}
|
|
created := time.Now().UTC().Truncate(time.Microsecond)
|
|
user := model.User{ID: id, Username: username, DisplayName: displayName, CreatedAt: created}
|
|
_, err = s.pool.Exec(ctx, `
|
|
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
|
VALUES ($1::uuid, $2, $3, $4, $5)`,
|
|
user.ID, user.Username, user.DisplayName, passwordHash, user.CreatedAt)
|
|
if err != nil {
|
|
return model.User{}, classify(err)
|
|
}
|
|
return s.UserByID(ctx, user.ID)
|
|
}
|
|
|
|
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
|
|
id, ok := model.NormalizeUUID(id)
|
|
if !ok {
|
|
return model.User{}, model.ErrNotFound
|
|
}
|
|
user, _, err := s.scanUser(ctx, `
|
|
SELECT id::text, username, display_name, created_at, password_hash
|
|
FROM users WHERE id = $1::uuid`, id)
|
|
return user, err
|
|
}
|
|
|
|
func (s *Store) UserByUsername(ctx context.Context, username string) (model.User, string, error) {
|
|
if !model.ValidUsername(username) {
|
|
return model.User{}, "", model.ErrNotFound
|
|
}
|
|
return s.scanUser(ctx, `
|
|
SELECT id::text, username, display_name, created_at, password_hash
|
|
FROM users WHERE username = $1`, username)
|
|
}
|
|
|
|
func (s *Store) CreateChat(ctx context.Context, caller, title string, memberIDs []string) (model.Chat, error) {
|
|
if !model.ValidLabel(title, 100) || len(memberIDs) < 1 || len(memberIDs) > 100 {
|
|
return model.Chat{}, model.ErrInvalid
|
|
}
|
|
caller, ok := model.NormalizeUUID(caller)
|
|
if !ok {
|
|
return model.Chat{}, model.ErrInvalid
|
|
}
|
|
seen := make(map[string]struct{}, len(memberIDs))
|
|
members := make([]string, 0, len(memberIDs))
|
|
callerSeen := false
|
|
for _, raw := range memberIDs {
|
|
id, ok := model.NormalizeUUID(raw)
|
|
if !ok {
|
|
return model.Chat{}, model.ErrInvalid
|
|
}
|
|
if _, dup := seen[id]; dup {
|
|
return model.Chat{}, model.ErrInvalid
|
|
}
|
|
seen[id] = struct{}{}
|
|
if id == caller {
|
|
callerSeen = true
|
|
}
|
|
members = append(members, id)
|
|
}
|
|
if !callerSeen {
|
|
return model.Chat{}, model.ErrInvalid
|
|
}
|
|
id, err := model.NewID()
|
|
if err != nil {
|
|
return model.Chat{}, err
|
|
}
|
|
created := time.Now().UTC().Truncate(time.Microsecond)
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return model.Chat{}, classify(err)
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)`, id, title, created); err != nil {
|
|
return model.Chat{}, classify(err)
|
|
}
|
|
tag, err := tx.Exec(ctx, `
|
|
INSERT INTO chat_members (chat_id, user_id, position)
|
|
SELECT $1::uuid, ord.id::uuid, ord.pos::int - 1
|
|
FROM unnest($2::text[]) WITH ORDINALITY AS ord(id, pos)
|
|
JOIN users AS u ON u.id = ord.id::uuid`, id, members)
|
|
if err != nil {
|
|
return model.Chat{}, classify(err)
|
|
}
|
|
if int(tag.RowsAffected()) != len(members) {
|
|
return model.Chat{}, model.ErrInvalid
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return model.Chat{}, classify(err)
|
|
}
|
|
return model.Chat{ID: id, Title: title, MemberIDs: members, CreatedAt: created}, nil
|
|
}
|
|
|
|
func (s *Store) Chat(ctx context.Context, chatID, userID string) (model.Chat, error) {
|
|
chatID, ok := model.NormalizeUUID(chatID)
|
|
if !ok {
|
|
return model.Chat{}, model.ErrInvalid
|
|
}
|
|
userID, ok = model.NormalizeUUID(userID)
|
|
if !ok {
|
|
return model.Chat{}, model.ErrInvalid
|
|
}
|
|
var chat model.Chat
|
|
err := s.pool.QueryRow(ctx, `
|
|
SELECT c.id::text, c.title, c.created_at,
|
|
COALESCE((
|
|
SELECT array_agg(cm.user_id::text ORDER BY cm.position)
|
|
FROM chat_members AS cm WHERE cm.chat_id = c.id
|
|
), '{}'::text[])
|
|
FROM chats AS c
|
|
JOIN chat_members AS mine ON mine.chat_id = c.id AND mine.user_id = $2::uuid
|
|
WHERE c.id = $1::uuid`, chatID, userID).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
|
if err != nil {
|
|
return model.Chat{}, classify(err)
|
|
}
|
|
chat.CreatedAt = chat.CreatedAt.UTC()
|
|
if chat.MemberIDs == nil {
|
|
chat.MemberIDs = []string{}
|
|
}
|
|
return chat, nil
|
|
}
|
|
|
|
func (s *Store) ListChats(ctx context.Context, userID string, limit int, cursor *model.Cursor) ([]model.Chat, *string, error) {
|
|
userID, ok := model.NormalizeUUID(userID)
|
|
if !ok {
|
|
return nil, nil, model.ErrInvalid
|
|
}
|
|
if cursor != nil && cursor.Resource != model.ResourceChats {
|
|
return nil, nil, model.ErrInvalid
|
|
}
|
|
var afterTime *time.Time
|
|
var afterID *string
|
|
if cursor != nil {
|
|
t := cursor.Time
|
|
id := cursor.ID
|
|
afterTime = &t
|
|
afterID = &id
|
|
}
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT c.id::text, c.title, c.created_at,
|
|
COALESCE((
|
|
SELECT array_agg(cm.user_id::text ORDER BY cm.position)
|
|
FROM chat_members AS cm WHERE cm.chat_id = c.id
|
|
), '{}'::text[])
|
|
FROM chats AS c
|
|
JOIN chat_members AS mine ON mine.chat_id = c.id AND mine.user_id = $1::uuid
|
|
WHERE $2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid)
|
|
ORDER BY c.created_at, c.id
|
|
LIMIT $4`, userID, afterTime, afterID, limit+1)
|
|
if err != nil {
|
|
return nil, nil, classify(err)
|
|
}
|
|
defer rows.Close()
|
|
items := make([]model.Chat, 0)
|
|
for rows.Next() {
|
|
var chat model.Chat
|
|
if err := rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
|
|
return nil, nil, classify(err)
|
|
}
|
|
chat.CreatedAt = chat.CreatedAt.UTC()
|
|
if chat.MemberIDs == nil {
|
|
chat.MemberIDs = []string{}
|
|
}
|
|
items = append(items, chat)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, nil, classify(err)
|
|
}
|
|
return pageChats(items, limit)
|
|
}
|
|
|
|
func (s *Store) AddMessage(ctx context.Context, chatID, senderID, text string) (model.Message, error) {
|
|
if !model.ValidLabel(text, 4000) {
|
|
return model.Message{}, model.ErrInvalid
|
|
}
|
|
chatID, ok := model.NormalizeUUID(chatID)
|
|
if !ok {
|
|
return model.Message{}, model.ErrInvalid
|
|
}
|
|
senderID, ok = model.NormalizeUUID(senderID)
|
|
if !ok {
|
|
return model.Message{}, model.ErrInvalid
|
|
}
|
|
id, err := model.NewID()
|
|
if err != nil {
|
|
return model.Message{}, err
|
|
}
|
|
created := time.Now().UTC().Truncate(time.Microsecond)
|
|
var msg model.Message
|
|
err = s.pool.QueryRow(ctx, `
|
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
|
SELECT $1::uuid, $2::uuid, $3::uuid, $4, $5
|
|
WHERE EXISTS (
|
|
SELECT 1 FROM chat_members
|
|
WHERE chat_id = $2::uuid AND user_id = $3::uuid
|
|
)
|
|
RETURNING id::text, chat_id::text, sender_id::text, text, created_at`,
|
|
id, chatID, senderID, text, created).Scan(&msg.ID, &msg.ChatID, &msg.SenderID, &msg.Text, &msg.CreatedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return model.Message{}, model.ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return model.Message{}, classify(err)
|
|
}
|
|
msg.CreatedAt = msg.CreatedAt.UTC()
|
|
return msg, nil
|
|
}
|
|
|
|
func (s *Store) ListMessages(ctx context.Context, chatID, userID string, limit int, cursor *model.Cursor) ([]model.Message, *string, error) {
|
|
chatID, ok := model.NormalizeUUID(chatID)
|
|
if !ok {
|
|
return nil, nil, model.ErrInvalid
|
|
}
|
|
userID, ok = model.NormalizeUUID(userID)
|
|
if !ok {
|
|
return nil, nil, model.ErrInvalid
|
|
}
|
|
if cursor != nil && (cursor.Resource != model.ResourceMessages || cursor.ChatID != chatID) {
|
|
return nil, nil, model.ErrInvalid
|
|
}
|
|
if _, err := s.Chat(ctx, chatID, userID); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
var afterTime *time.Time
|
|
var afterID *string
|
|
if cursor != nil {
|
|
t := cursor.Time
|
|
id := cursor.ID
|
|
afterTime = &t
|
|
afterID = &id
|
|
}
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = $1::uuid
|
|
AND ($2::timestamptz IS NULL OR (created_at, id) > ($2, $3::uuid))
|
|
ORDER BY created_at, id
|
|
LIMIT $4`, chatID, afterTime, afterID, limit+1)
|
|
if err != nil {
|
|
return nil, nil, classify(err)
|
|
}
|
|
defer rows.Close()
|
|
items := make([]model.Message, 0)
|
|
for rows.Next() {
|
|
var msg model.Message
|
|
if err := rows.Scan(&msg.ID, &msg.ChatID, &msg.SenderID, &msg.Text, &msg.CreatedAt); err != nil {
|
|
return nil, nil, classify(err)
|
|
}
|
|
msg.CreatedAt = msg.CreatedAt.UTC()
|
|
items = append(items, msg)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, nil, classify(err)
|
|
}
|
|
return pageMessages(items, limit, chatID)
|
|
}
|
|
|
|
func (s *Store) scanUser(ctx context.Context, query string, arg any) (model.User, string, error) {
|
|
var user model.User
|
|
var hash string
|
|
err := s.pool.QueryRow(ctx, query, arg).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
|
|
if err != nil {
|
|
return model.User{}, "", classify(err)
|
|
}
|
|
user.CreatedAt = user.CreatedAt.UTC()
|
|
return user, hash, nil
|
|
}
|
|
|
|
func pageMessages(items []model.Message, limit int, chatID string) ([]model.Message, *string, error) {
|
|
if len(items) <= limit {
|
|
return items, nil, nil
|
|
}
|
|
items = items[:limit]
|
|
last := items[len(items)-1]
|
|
token, err := model.EncodeCursor(model.Cursor{
|
|
Resource: model.ResourceMessages,
|
|
ChatID: chatID,
|
|
Time: last.CreatedAt,
|
|
ID: last.ID,
|
|
})
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return items, &token, nil
|
|
}
|
|
|
|
func pageChats(items []model.Chat, limit int) ([]model.Chat, *string, error) {
|
|
if len(items) <= limit {
|
|
return items, nil, nil
|
|
}
|
|
items = items[:limit]
|
|
last := items[len(items)-1]
|
|
token, err := model.EncodeCursor(model.Cursor{
|
|
Resource: model.ResourceChats,
|
|
Time: last.CreatedAt,
|
|
ID: last.ID,
|
|
})
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return items, &token, nil
|
|
}
|
|
|
|
func classify(err error) error {
|
|
if err == nil || errors.Is(err, model.ErrInvalid) || errors.Is(err, model.ErrConflict) || errors.Is(err, model.ErrNotFound) || errors.Is(err, model.ErrUnavailable) {
|
|
return err
|
|
}
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return model.ErrNotFound
|
|
}
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) {
|
|
switch pgErr.Code {
|
|
case "23505":
|
|
return model.ErrConflict
|
|
case "23503", "23514", "23502", "22P02":
|
|
return model.ErrInvalid
|
|
default:
|
|
return model.ErrUnavailable
|
|
}
|
|
}
|
|
return model.ErrUnavailable
|
|
}
|