forked from mtusi2026/mtusi2026lab5
feat: port lab4 implementation
This commit is contained in:
@@ -0,0 +1,286 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
"mtusi2026-messenger/internal/postgres"
|
||||
s3store "mtusi2026-messenger/internal/s3"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAttachmentNotFound = errors.New("attachment not found")
|
||||
ErrAttachmentNotReady = errors.New("attachment not ready")
|
||||
ErrInvalidImage = errors.New("invalid image")
|
||||
ErrInvalidSize = errors.New("invalid size")
|
||||
ErrUploadReadTimeout = errors.New("upload body read timed out")
|
||||
)
|
||||
|
||||
type attachmentQueries interface {
|
||||
CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error)
|
||||
GetAttachmentByID(ctx context.Context, id uuid.UUID) (db.Attachment, error)
|
||||
IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error)
|
||||
MarkAttachmentReady(ctx context.Context, id uuid.UUID) (db.Attachment, error)
|
||||
}
|
||||
|
||||
type AttachmentService struct {
|
||||
q attachmentQueries
|
||||
s3 *s3store.Client
|
||||
maxBytes int
|
||||
maxPixels int
|
||||
decodeSlot chan struct{}
|
||||
}
|
||||
|
||||
func NewAttachmentService(
|
||||
q attachmentQueries,
|
||||
s3 *s3store.Client,
|
||||
maxBytes, maxPixels int,
|
||||
) *AttachmentService {
|
||||
return &AttachmentService{
|
||||
q: q,
|
||||
s3: s3,
|
||||
maxBytes: maxBytes,
|
||||
maxPixels: maxPixels,
|
||||
decodeSlot: make(chan struct{}, 1),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Upload(
|
||||
ctx context.Context,
|
||||
userID, chatID uuid.UUID,
|
||||
filename string,
|
||||
body io.Reader,
|
||||
contentType string,
|
||||
) (model.Attachment, error) {
|
||||
if err := s.ensureMember(ctx, userID, chatID); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
tmp, err := os.CreateTemp("", "upload-*.tmp")
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
defer func() {
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(tmp.Name())
|
||||
}()
|
||||
|
||||
hasher := sha256.New()
|
||||
size, err := io.Copy(io.MultiWriter(tmp, hasher), body)
|
||||
if err != nil {
|
||||
var maxBytesErr *http.MaxBytesError
|
||||
if errors.As(err, &maxBytesErr) {
|
||||
return model.Attachment{}, ErrInvalidSize
|
||||
}
|
||||
var networkErr net.Error
|
||||
if errors.As(err, &networkErr) && networkErr.Timeout() {
|
||||
return model.Attachment{}, ErrUploadReadTimeout
|
||||
}
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
if size > int64(s.maxBytes) {
|
||||
return model.Attachment{}, ErrInvalidSize
|
||||
}
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
detectedType, err := s.checkImage(ctx, tmp, contentType)
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
hash := hex.EncodeToString(hasher.Sum(nil))
|
||||
key := "chats/" + chatID.String() + "/attachments/" + id.String()
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
_, err = s.q.CreateAttachment(ctx, db.CreateAttachmentParams{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
OwnerID: userID,
|
||||
S3Key: key,
|
||||
Filename: filename,
|
||||
ContentType: db.AttachmentContentType(detectedType),
|
||||
SizeBytes: int(size),
|
||||
Sha256: hash,
|
||||
ErrorCode: "",
|
||||
})
|
||||
if postgres.IsNotFound(err) {
|
||||
return model.Attachment{}, ErrAttachmentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
if err := s.s3.Put(ctx, key, tmp, size, string(detectedType)); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
row, err := s.q.MarkAttachmentReady(ctx, id)
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
return model.Attachment{
|
||||
ID: row.ID,
|
||||
ChatID: row.ChatID,
|
||||
OwnerID: row.OwnerID,
|
||||
Filename: row.Filename,
|
||||
ContentType: model.ContentType(row.ContentType),
|
||||
SizeBytes: row.SizeBytes,
|
||||
Sha256: row.Sha256,
|
||||
Status: model.AttachmentStatus(row.Status),
|
||||
ErrorCode: row.ErrorCode,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Get(
|
||||
ctx context.Context,
|
||||
userID, attachmentID uuid.UUID,
|
||||
) (model.Attachment, error) {
|
||||
row, err := s.q.GetAttachmentByID(ctx, attachmentID)
|
||||
if postgres.IsNotFound(err) {
|
||||
return model.Attachment{}, ErrAttachmentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
if err := s.ensureMember(ctx, userID, row.ChatID); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
return model.Attachment{
|
||||
ID: row.ID,
|
||||
ChatID: row.ChatID,
|
||||
OwnerID: row.OwnerID,
|
||||
Filename: row.Filename,
|
||||
ContentType: model.ContentType(row.ContentType),
|
||||
SizeBytes: row.SizeBytes,
|
||||
Sha256: row.Sha256,
|
||||
Status: model.AttachmentStatus(row.Status),
|
||||
ErrorCode: row.ErrorCode,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) GetContent(
|
||||
ctx context.Context,
|
||||
userID, attachmentID uuid.UUID,
|
||||
) ([]byte, model.ContentType, error) {
|
||||
row, err := s.q.GetAttachmentByID(ctx, attachmentID)
|
||||
if postgres.IsNotFound(err) {
|
||||
return nil, "", ErrAttachmentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if err := s.ensureMember(ctx, userID, row.ChatID); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if model.AttachmentStatus(row.Status) != model.AttachmentStatusReady {
|
||||
return nil, "", ErrAttachmentNotReady
|
||||
}
|
||||
|
||||
out, err := s.s3.Get(ctx, row.S3Key)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer out.Body.Close()
|
||||
|
||||
data, err := io.ReadAll(out.Body)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return data, model.ContentType(row.ContentType), nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) checkImage(ctx context.Context, r io.ReadSeeker, contentType string) (model.ContentType, error) {
|
||||
cfg, format, err := image.DecodeConfig(r)
|
||||
if err != nil {
|
||||
return "", ErrInvalidImage
|
||||
}
|
||||
|
||||
if cfg.Width <= 0 || cfg.Height <= 0 {
|
||||
return "", ErrInvalidImage
|
||||
}
|
||||
if cfg.Width > s.maxPixels/cfg.Height {
|
||||
return "", ErrInvalidSize
|
||||
}
|
||||
|
||||
var detectedType model.ContentType
|
||||
switch format {
|
||||
case "png":
|
||||
if contentType != string(model.ContentTypePNG) {
|
||||
return "", ErrInvalidImage
|
||||
}
|
||||
detectedType = model.ContentTypePNG
|
||||
case "jpeg":
|
||||
if contentType != string(model.ContentTypeJPEG) {
|
||||
return "", ErrInvalidImage
|
||||
}
|
||||
detectedType = model.ContentTypeJPEG
|
||||
default:
|
||||
return "", ErrInvalidImage
|
||||
}
|
||||
|
||||
select {
|
||||
case s.decodeSlot <- struct{}{}:
|
||||
defer func() { <-s.decodeSlot }()
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, _, err := image.Decode(r); err != nil {
|
||||
return "", ErrInvalidImage
|
||||
}
|
||||
|
||||
return detectedType, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID uuid.UUID) error {
|
||||
member, err := s.q.IsChatMember(ctx, db.IsChatMemberParams{
|
||||
ChatID: chatID,
|
||||
UserID: userID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return ErrAttachmentNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"mtusi2026-messenger/internal/credentials"
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
"mtusi2026-messenger/internal/postgres"
|
||||
|
||||
"github.com/google/uuid"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const sessionCacheTTL = 60 * time.Second
|
||||
const cacheOpTimeout = 300 * time.Millisecond
|
||||
|
||||
var (
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrSessionCacheUnavailable = errors.New("session cache unavailable")
|
||||
)
|
||||
|
||||
type authQueries interface {
|
||||
CreateSession(ctx context.Context, arg db.CreateSessionParams) error
|
||||
DeleteSession(ctx context.Context, tokenHash string) (int64, error)
|
||||
GetActiveSession(ctx context.Context, tokenHash string) (db.GetActiveSessionRow, error)
|
||||
GetUserByUsername(ctx context.Context, username string) (db.User, error)
|
||||
}
|
||||
|
||||
type AuthService struct {
|
||||
q authQueries
|
||||
cache *goredis.Client
|
||||
sessionTTL time.Duration
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewAuthService(q authQueries, cache *goredis.Client, sessionTTL time.Duration, log *slog.Logger) *AuthService {
|
||||
return &AuthService{
|
||||
q: q,
|
||||
cache: cache,
|
||||
sessionTTL: sessionTTL,
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
var dummyHash, _ = credentials.HashPassword("dummy-password-for-timing")
|
||||
|
||||
func (s *AuthService) Login(ctx context.Context, username, plain string) (model.Session, error) {
|
||||
user, err := s.q.GetUserByUsername(ctx, username)
|
||||
if postgres.IsNotFound(err) {
|
||||
_ = credentials.VerifyPassword(dummyHash, plain)
|
||||
return model.Session{}, ErrInvalidCredentials
|
||||
}
|
||||
if err != nil {
|
||||
return model.Session{}, err
|
||||
}
|
||||
|
||||
if err := credentials.VerifyPassword(user.PasswordHash, plain); err != nil {
|
||||
if errors.Is(err, credentials.ErrPasswordMismatch) {
|
||||
return model.Session{}, ErrInvalidCredentials
|
||||
}
|
||||
return model.Session{}, err
|
||||
}
|
||||
|
||||
token := credentials.NewToken()
|
||||
expiresAt := time.Now().UTC().Add(s.sessionTTL)
|
||||
|
||||
err = s.q.CreateSession(ctx, db.CreateSessionParams{
|
||||
TokenHash: credentials.HashToken(token),
|
||||
UserID: user.ID,
|
||||
ExpiresAt: expiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Session{}, err
|
||||
}
|
||||
|
||||
return model.Session{
|
||||
Token: token,
|
||||
ExpiresAt: expiresAt,
|
||||
User: model.User{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: user.CreatedAt.UTC(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
tokenHash := credentials.HashToken(token)
|
||||
key := cacheKey(tokenHash)
|
||||
|
||||
if id, ok := s.cacheGet(ctx, key); ok {
|
||||
return id, nil
|
||||
}
|
||||
|
||||
row, err := s.q.GetActiveSession(ctx, tokenHash)
|
||||
if postgres.IsNotFound(err) {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
|
||||
s.cacheSet(ctx, key, row.UserID, min(time.Until(row.ExpiresAt), sessionCacheTTL))
|
||||
|
||||
return row.UserID, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
tokenHash := credentials.HashToken(token)
|
||||
|
||||
n, err := s.q.DeleteSession(ctx, tokenHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.cacheDel(ctx, cacheKey(tokenHash)); err != nil {
|
||||
return ErrSessionCacheUnavailable
|
||||
}
|
||||
|
||||
if n == 0 {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cacheKey(tokenHash string) string {
|
||||
return "session:" + tokenHash
|
||||
}
|
||||
|
||||
func (s *AuthService) cacheGet(ctx context.Context, key string) (uuid.UUID, bool) {
|
||||
if s.cache == nil {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
||||
defer cancel()
|
||||
|
||||
val, err := s.cache.Get(cctx, key).Result()
|
||||
switch {
|
||||
case err == nil:
|
||||
id, perr := uuid.Parse(val)
|
||||
if perr != nil {
|
||||
s.log.Warn("session cache value is not a uuid", "error", perr)
|
||||
return uuid.Nil, false
|
||||
}
|
||||
s.log.Debug("session cache hit")
|
||||
return id, true
|
||||
case errors.Is(err, goredis.Nil):
|
||||
s.log.Debug("session cache miss")
|
||||
default:
|
||||
s.log.Warn("session cache get failed, falling back to database", "error", err)
|
||||
}
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
func (s *AuthService) cacheSet(ctx context.Context, key string, id uuid.UUID, ttl time.Duration) {
|
||||
if s.cache == nil || ttl <= 0 {
|
||||
return
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := s.cache.Set(cctx, key, id.String(), ttl).Err(); err != nil {
|
||||
s.log.Warn("session cache set failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AuthService) cacheDel(ctx context.Context, key string) error {
|
||||
if s.cache == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := s.cache.Del(cctx, key).Err(); err != nil {
|
||||
s.log.Warn("session cache delete failed", "error", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
"mtusi2026-messenger/internal/postgres"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrChatNotFound = errors.New("chat not found")
|
||||
ErrNotChatMember = errors.New("caller must be a member of member_ids")
|
||||
ErrDuplicateMember = errors.New("member_ids contains duplicates")
|
||||
ErrUnknownMember = errors.New("member_ids contains unknown user")
|
||||
)
|
||||
|
||||
type chatQueries interface {
|
||||
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)
|
||||
ListChatsAfter(ctx context.Context, arg db.ListChatsAfterParams) ([]db.ListChatsAfterRow, error)
|
||||
ListChatsFirstPage(ctx context.Context, arg db.ListChatsFirstPageParams) ([]db.ListChatsFirstPageRow, error)
|
||||
}
|
||||
|
||||
type ChatService struct {
|
||||
pool txBeginner
|
||||
q chatQueries
|
||||
withTx func(pgx.Tx) chatQueries
|
||||
}
|
||||
|
||||
func NewChatService(pool *pgxpool.Pool, q *db.Queries) *ChatService {
|
||||
return &ChatService{
|
||||
pool: pool,
|
||||
q: q,
|
||||
withTx: func(tx pgx.Tx) chatQueries {
|
||||
return q.WithTx(tx)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
title string,
|
||||
memberIDs []uuid.UUID,
|
||||
) (model.Chat, error) {
|
||||
if !slices.Contains(memberIDs, userID) {
|
||||
return model.Chat{}, ErrNotChatMember
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
q := s.withTx(tx)
|
||||
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
row, err := q.CreateChat(ctx, db.CreateChatParams{
|
||||
ID: id,
|
||||
Title: title,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
err = q.AddChatMembers(ctx, db.AddChatMembersParams{
|
||||
ChatID: row.ID,
|
||||
UserIds: memberIDs,
|
||||
})
|
||||
switch postgres.ErrCode(err) {
|
||||
case postgres.CodeUniqueViolation:
|
||||
return model.Chat{}, ErrDuplicateMember
|
||||
case postgres.CodeForeignKeyViolation:
|
||||
return model.Chat{}, ErrUnknownMember
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
ids := slices.Clone(memberIDs)
|
||||
slices.SortFunc(ids, func(a, b uuid.UUID) int {
|
||||
return bytes.Compare(a[:], b[:])
|
||||
})
|
||||
|
||||
return model.Chat{
|
||||
ID: row.ID,
|
||||
Title: row.Title,
|
||||
CreatedAt: row.CreatedAt,
|
||||
MemberIDs: ids,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
chatID uuid.UUID,
|
||||
) (model.Chat, error) {
|
||||
row, err := s.q.GetChat(ctx, db.GetChatParams{
|
||||
ID: chatID,
|
||||
UserID: userID,
|
||||
})
|
||||
if postgres.IsNotFound(err) {
|
||||
return model.Chat{}, ErrChatNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
return model.Chat{
|
||||
ID: row.ID,
|
||||
Title: row.Title,
|
||||
CreatedAt: row.CreatedAt,
|
||||
MemberIDs: row.MemberIds,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) List(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
limit int,
|
||||
cursor *string,
|
||||
) ([]model.Chat, *string, error) {
|
||||
var chats []model.Chat
|
||||
|
||||
if cursor == nil {
|
||||
rows, err := s.q.ListChatsFirstPage(ctx, db.ListChatsFirstPageParams{
|
||||
UserID: userID,
|
||||
Lim: limit + 1,
|
||||
})
|
||||
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
|
||||
}
|
||||
|
||||
rows, err := s.q.ListChatsAfter(ctx, db.ListChatsAfterParams{
|
||||
UserID: userID,
|
||||
AfterCreatedAt: decoded.CreatedAt,
|
||||
AfterID: decoded.ID,
|
||||
Lim: limit + 1,
|
||||
})
|
||||
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
|
||||
if hasMore {
|
||||
last := chats[len(chats)-1]
|
||||
c := encodeCursor(Cursor{
|
||||
CreatedAt: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
})
|
||||
next = &c
|
||||
}
|
||||
|
||||
return chats, next, nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
func encodeCursor(cursor Cursor) string {
|
||||
data, _ := json.Marshal(cursor)
|
||||
return base64.RawURLEncoding.EncodeToString(data)
|
||||
}
|
||||
|
||||
func decodeCursor(raw string, chatID uuid.UUID) (Cursor, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(raw)
|
||||
if err != nil {
|
||||
return Cursor{}, ErrInvalidCursor
|
||||
}
|
||||
|
||||
var cursor Cursor
|
||||
if err := json.Unmarshal(data, &cursor); err != nil {
|
||||
return Cursor{}, ErrInvalidCursor
|
||||
}
|
||||
|
||||
if cursor.ID == uuid.Nil || cursor.CreatedAt.IsZero() || cursor.ChatID != chatID {
|
||||
return Cursor{}, ErrInvalidCursor
|
||||
}
|
||||
|
||||
return cursor, nil
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
"mtusi2026-messenger/internal/postgres"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrMessageChatNotFound = errors.New("chat not found")
|
||||
ErrIdempotencyKeyConflict = errors.New("idempotency key reused with different request")
|
||||
)
|
||||
|
||||
type messageQueries interface {
|
||||
CreateIdempotencyKey(ctx context.Context, arg db.CreateIdempotencyKeyParams) (int64, error)
|
||||
CreateMessage(ctx context.Context, arg db.CreateMessageParams) (db.Message, error)
|
||||
CreateMessageAttachment(ctx context.Context, arg db.CreateMessageAttachmentParams) error
|
||||
GetIdempotentMessage(ctx context.Context, arg db.GetIdempotentMessageParams) (db.GetIdempotentMessageRow, error)
|
||||
IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error)
|
||||
ListAttachmentsByIDs(ctx context.Context, arg db.ListAttachmentsByIDsParams) ([]db.AttachmentStatus, error)
|
||||
ListMessageAttachmentIDs(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error)
|
||||
ListMessageAttachmentsByMessageIDs(ctx context.Context, messageIDs []uuid.UUID) ([]db.ListMessageAttachmentsByMessageIDsRow, error)
|
||||
ListMessagesAfter(ctx context.Context, arg db.ListMessagesAfterParams) ([]db.Message, error)
|
||||
ListMessagesFirstPage(ctx context.Context, arg db.ListMessagesFirstPageParams) ([]db.Message, error)
|
||||
}
|
||||
|
||||
type MessageService struct {
|
||||
pool txBeginner
|
||||
q *db.Queries
|
||||
withTx func(pgx.Tx) messageQueries
|
||||
}
|
||||
|
||||
func NewMessageService(pool *pgxpool.Pool, q *db.Queries) *MessageService {
|
||||
return &MessageService{
|
||||
pool: pool,
|
||||
q: q,
|
||||
withTx: func(tx pgx.Tx) messageQueries {
|
||||
return q.WithTx(tx)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessageService) Create(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
chatID uuid.UUID,
|
||||
key string,
|
||||
text string,
|
||||
attachmentIDs []uuid.UUID,
|
||||
) (model.Message, error) {
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
if len(attachmentIDs) > 0 {
|
||||
statuses, err := s.q.ListAttachmentsByIDs(ctx, db.ListAttachmentsByIDsParams{
|
||||
ChatID: chatID,
|
||||
Ids: attachmentIDs,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if len(statuses) != len(attachmentIDs) {
|
||||
return model.Message{}, ErrAttachmentNotFound
|
||||
}
|
||||
for _, status := range statuses {
|
||||
if status != db.AttachmentStatusReady {
|
||||
return model.Message{}, ErrAttachmentNotReady
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hashInput := text + "|" + normalizeAttachmentIDs(attachmentIDs)
|
||||
sum := sha256.Sum256([]byte(hashInput))
|
||||
hash := hex.EncodeToString(sum[:])
|
||||
path := "/api/v1/chats/" + chatID.String() + "/messages"
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
q := s.withTx(tx)
|
||||
|
||||
inserted, err := q.CreateIdempotencyKey(ctx, db.CreateIdempotencyKeyParams{
|
||||
UserID: userID,
|
||||
Method: http.MethodPost,
|
||||
Path: path,
|
||||
Key: key,
|
||||
RequestHash: hash,
|
||||
MessageID: id,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
if inserted == 0 {
|
||||
isMember, err := q.IsChatMember(ctx, db.IsChatMemberParams{
|
||||
ChatID: chatID,
|
||||
UserID: userID,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if !isMember {
|
||||
return model.Message{}, ErrMessageChatNotFound
|
||||
}
|
||||
|
||||
stored, err := q.GetIdempotentMessage(ctx, db.GetIdempotentMessageParams{
|
||||
UserID: userID,
|
||||
Method: http.MethodPost,
|
||||
Path: path,
|
||||
Key: key,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if stored.RequestHash != hash {
|
||||
return model.Message{}, ErrIdempotencyKeyConflict
|
||||
}
|
||||
|
||||
storedAttachmentIDs, err := q.ListMessageAttachmentIDs(ctx, stored.ID)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
return model.Message{
|
||||
ID: stored.ID,
|
||||
ChatID: stored.ChatID,
|
||||
SenderID: stored.SenderID,
|
||||
Text: stored.Text,
|
||||
AttachmentIDs: storedAttachmentIDs,
|
||||
CreatedAt: stored.CreatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
row, err := 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
|
||||
}
|
||||
|
||||
for i, attachmentID := range attachmentIDs {
|
||||
if err := q.CreateMessageAttachment(ctx, db.CreateMessageAttachmentParams{
|
||||
MessageID: id,
|
||||
AttachmentID: attachmentID,
|
||||
Position: i,
|
||||
}); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
return model.Message{
|
||||
ID: row.ID,
|
||||
ChatID: row.ChatID,
|
||||
SenderID: row.SenderID,
|
||||
Text: row.Text,
|
||||
AttachmentIDs: attachmentIDs,
|
||||
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 rows []db.Message
|
||||
|
||||
if cursor == nil {
|
||||
rows, err = s.q.ListMessagesFirstPage(ctx, db.ListMessagesFirstPageParams{
|
||||
ChatID: chatID,
|
||||
Lim: limit + 1,
|
||||
})
|
||||
} else {
|
||||
decoded, derr := decodeCursor(*cursor, chatID)
|
||||
if derr != nil {
|
||||
return nil, nil, ErrInvalidCursor
|
||||
}
|
||||
|
||||
rows, err = s.q.ListMessagesAfter(ctx, db.ListMessagesAfterParams{
|
||||
ChatID: chatID,
|
||||
AfterCreatedAt: decoded.CreatedAt,
|
||||
AfterID: decoded.ID,
|
||||
Lim: limit + 1,
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
hasMore := len(rows) > limit
|
||||
if hasMore {
|
||||
rows = rows[:limit]
|
||||
}
|
||||
|
||||
attachmentsByMessage := make(map[uuid.UUID][]uuid.UUID, len(rows))
|
||||
if len(rows) > 0 {
|
||||
messageIDs := make([]uuid.UUID, len(rows))
|
||||
for i, r := range rows {
|
||||
messageIDs[i] = r.ID
|
||||
}
|
||||
|
||||
links, err := s.q.ListMessageAttachmentsByMessageIDs(ctx, messageIDs)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, l := range links {
|
||||
attachmentsByMessage[l.MessageID] = append(attachmentsByMessage[l.MessageID], l.AttachmentID)
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
AttachmentIDs: attachmentsByMessage[r.ID],
|
||||
CreatedAt: r.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
var next *string
|
||||
if hasMore {
|
||||
last := messages[len(messages)-1]
|
||||
c := encodeCursor(Cursor{
|
||||
ChatID: chatID,
|
||||
CreatedAt: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
})
|
||||
next = &c
|
||||
}
|
||||
|
||||
return messages, next, nil
|
||||
}
|
||||
|
||||
func normalizeAttachmentIDs(ids []uuid.UUID) string {
|
||||
if len(ids) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
parts := make([]string, len(ids))
|
||||
for i, id := range ids {
|
||||
parts[i] = id.String()
|
||||
}
|
||||
sort.Strings(parts)
|
||||
|
||||
return strings.Join(parts, ",")
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type txBeginner interface {
|
||||
Begin(ctx context.Context) (pgx.Tx, error)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026-messenger/internal/credentials"
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
"mtusi2026-messenger/internal/postgres"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUsernameTaken = errors.New("username already taken")
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
)
|
||||
|
||||
type userQueries interface {
|
||||
CreateUser(ctx context.Context, arg db.CreateUserParams) (db.CreateUserRow, error)
|
||||
GetUser(ctx context.Context, id uuid.UUID) (db.GetUserRow, error)
|
||||
}
|
||||
|
||||
type UserService struct {
|
||||
q userQueries
|
||||
}
|
||||
|
||||
func NewUserService(q userQueries) *UserService {
|
||||
return &UserService{q: q}
|
||||
}
|
||||
|
||||
func (s *UserService) Create(
|
||||
ctx context.Context,
|
||||
username, displayName, plain string,
|
||||
) (model.User, error) {
|
||||
hash, err := credentials.HashPassword(plain)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
|
||||
row, err := s.q.CreateUser(ctx, db.CreateUserParams{
|
||||
ID: id,
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
PasswordHash: hash,
|
||||
})
|
||||
if err != nil {
|
||||
if postgres.ErrCode(err) == postgres.CodeUniqueViolation {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
return model.User{}, err
|
||||
}
|
||||
|
||||
return model.User{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
CreatedAt: row.CreatedAt.UTC(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *UserService) GetByID(ctx context.Context, id uuid.UUID) (model.User, error) {
|
||||
row, err := s.q.GetUser(ctx, id)
|
||||
if postgres.IsNotFound(err) {
|
||||
return model.User{}, ErrUserNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
|
||||
return model.User{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
CreatedAt: row.CreatedAt.UTC(),
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user