forked from mtusi2026/mtusi2026lab4
feat: implement lab4 persistent attachments and replicated API
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
type AttachmentStore struct{ Pool *pgxpool.Pool }
|
||||
|
||||
func NewAttachmentStore(p *pgxpool.Pool) *AttachmentStore { return &AttachmentStore{p} }
|
||||
func (s *AttachmentStore) Create(ctx context.Context, a model.Attachment) error {
|
||||
_, err := s.Pool.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256, a.ObjectKey, a.CreatedAt, a.UpdatedAt)
|
||||
return err
|
||||
}
|
||||
func (s *AttachmentStore) GetForUser(ctx context.Context, id, user uuid.UUID) (model.Attachment, error) {
|
||||
var a model.Attachment
|
||||
err := s.Pool.QueryRow(ctx, `SELECT a.id,a.chat_id,a.owner_id,a.filename,a.content_type,a.size_bytes,a.sha256,a.object_key,a.created_at,a.updated_at FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id WHERE a.id=$1 AND cm.user_id=$2`, id, user).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.ObjectKey, &a.CreatedAt, &a.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return a, ErrAttachmentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
a.Status = "ready"
|
||||
a.Variants = []any{}
|
||||
return a, nil
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrUsernameTaken = errors.New("username already exists")
|
||||
ErrSessionNotFound = errors.New("session not found")
|
||||
)
|
||||
|
||||
type AuthStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAuthStore(pool *pgxpool.Pool) *AuthStore {
|
||||
return &AuthStore{pool: pool}
|
||||
}
|
||||
|
||||
func (s *AuthStore) CreateUser(
|
||||
ctx context.Context,
|
||||
user model.User,
|
||||
passwordHash string,
|
||||
) error {
|
||||
const query = `
|
||||
INSERT INTO users
|
||||
(id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`
|
||||
|
||||
_, err := s.pool.Exec(ctx, query,
|
||||
user.ID,
|
||||
user.Username,
|
||||
user.DisplayName,
|
||||
passwordHash,
|
||||
user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return ErrUsernameTaken
|
||||
}
|
||||
return fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (model.User, string, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name,
|
||||
password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
|
||||
var user model.User
|
||||
var passwordHash string
|
||||
|
||||
err := s.pool.QueryRow(ctx, query, username).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&passwordHash,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, "", ErrUserNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, "", fmt.Errorf("get user: %w", err)
|
||||
}
|
||||
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) GetUserByID(
|
||||
ctx context.Context,
|
||||
id uuid.UUID,
|
||||
) (model.User, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
var user model.User
|
||||
|
||||
err := s.pool.QueryRow(ctx, query, id).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrUserNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("get user by id: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func tokenHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *AuthStore) CreateSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
userID uuid.UUID,
|
||||
createdAt time.Time,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
const query = `
|
||||
INSERT INTO sessions
|
||||
(token_hash, user_id, created_at, expires_at)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
`
|
||||
|
||||
_, err := s.pool.Exec(ctx, query,
|
||||
tokenHash(token),
|
||||
userID,
|
||||
createdAt,
|
||||
expiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) GetSessionUser(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (model.User, error) {
|
||||
const query = `
|
||||
SELECT u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1
|
||||
AND s.expires_at > NOW()
|
||||
`
|
||||
|
||||
var user model.User
|
||||
|
||||
err := s.pool.QueryRow(ctx, query, tokenHash(token)).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrSessionNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("get session: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) RevokeSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
const query = `
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1
|
||||
AND expires_at > NOW()
|
||||
`
|
||||
|
||||
result, err := s.pool.Exec(ctx, query, tokenHash(token))
|
||||
if err != nil {
|
||||
return fmt.Errorf("revoke session: %w", err)
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
return ErrSessionNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetActiveSessionUserID is the authoritative expiry/revocation check.
|
||||
// Redis only caches the public user profile; it never grants access on its own.
|
||||
func (s *AuthStore) GetActiveSessionUserID(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
var userID uuid.UUID
|
||||
err := s.pool.QueryRow(ctx, `SELECT user_id FROM sessions WHERE token_hash=$1 AND expires_at>NOW()`, tokenHash(token)).Scan(&userID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return uuid.Nil, ErrSessionNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("validate session: %w", err)
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrChatNotFound = errors.New("chat not found")
|
||||
ErrInvalidMember = errors.New("chat member does not exist")
|
||||
)
|
||||
|
||||
type ChatStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatStore(pool *pgxpool.Pool) *ChatStore {
|
||||
return &ChatStore{pool: pool}
|
||||
}
|
||||
|
||||
// CreateChat creates the chat and all its members in one transaction.
|
||||
// A failure inserting any member rolls back the entire chat.
|
||||
func (s *ChatStore) CreateChat(
|
||||
ctx context.Context,
|
||||
chat model.Chat,
|
||||
) error {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin chat transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
VALUES ($1, $2, $3)
|
||||
`, chat.ID, chat.Title, chat.CreatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
`, chat.ID, memberID)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23503" {
|
||||
return ErrInvalidMember
|
||||
}
|
||||
return fmt.Errorf("insert chat member: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit chat transaction: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetChatForUser returns a chat only if the user is a member.
|
||||
// Missing chats and inaccessible chats both return ErrChatNotFound.
|
||||
func (s *ChatStore) GetChatForUser(
|
||||
ctx context.Context,
|
||||
chatID uuid.UUID,
|
||||
userID uuid.UUID,
|
||||
) (model.Chat, error) {
|
||||
var chat model.Chat
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1 AND cm.user_id = $2
|
||||
`, chatID, userID).Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrChatNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, fmt.Errorf("get chat: %w", err)
|
||||
}
|
||||
|
||||
members, err := s.getMemberIDs(ctx, chat.ID)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
chat.MemberIDs = members
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) getMemberIDs(
|
||||
ctx context.Context,
|
||||
chatID uuid.UUID,
|
||||
) ([]uuid.UUID, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
ORDER BY user_id
|
||||
`, chatID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query chat members: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
members := make([]uuid.UUID, 0)
|
||||
|
||||
for rows.Next() {
|
||||
var memberID uuid.UUID
|
||||
if err := rows.Scan(&memberID); err != nil {
|
||||
return nil, fmt.Errorf("scan chat member: %w", err)
|
||||
}
|
||||
members = append(members, memberID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate chat members: %w", err)
|
||||
}
|
||||
|
||||
return members, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) ListChatsForUser(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
) ([]model.Chat, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = $1
|
||||
ORDER BY c.created_at, c.id
|
||||
`, userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
|
||||
chats := make([]model.Chat, 0)
|
||||
|
||||
for rows.Next() {
|
||||
var chat model.Chat
|
||||
if err := rows.Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("scan chat: %w", err)
|
||||
}
|
||||
chats = append(chats, chat)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("iterate chats: %w", err)
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
// A connection cannot be reused for another query until rows are closed.
|
||||
for i := range chats {
|
||||
members, err := s.getMemberIDs(ctx, chats[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chats[i].MemberIDs = members
|
||||
}
|
||||
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
// ExistsUser is used to validate members before creating a chat.
|
||||
func (s *ChatStore) ExistsUser(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
) (bool, error) {
|
||||
var exists bool
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT EXISTS(SELECT 1 FROM users WHERE id = $1)
|
||||
`, userID).Scan(&exists)
|
||||
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("check user existence: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// Kept here to document that chat timestamps are stored in UTC.
|
||||
var _ = time.UTC
|
||||
|
||||
// ListChatsPage uses (created_at,id) keyset pagination and fetches limit+1.
|
||||
func (s *ChatStore) ListChatsPage(ctx context.Context, userID uuid.UUID, limit int, cursorTime *time.Time, cursorID *uuid.UUID) ([]model.Chat, bool, error) {
|
||||
var rows pgx.Rows
|
||||
var err error
|
||||
if cursorTime == nil || cursorID == nil {
|
||||
rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 ORDER BY c.created_at,c.id LIMIT $2`, userID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 AND (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, userID, *cursorTime, *cursorID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
chats := make([]model.Chat, 0, limit+1)
|
||||
for rows.Next() {
|
||||
var c model.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
rows.Close()
|
||||
return nil, false, err
|
||||
}
|
||||
chats = append(chats, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, false, err
|
||||
}
|
||||
rows.Close()
|
||||
more := len(chats) > limit
|
||||
if more {
|
||||
chats = chats[:limit]
|
||||
}
|
||||
for i := range chats {
|
||||
members, err := s.getMemberIDs(ctx, chats[i].ID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
chats[i].MemberIDs = members
|
||||
}
|
||||
return chats, more, nil
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
func TestConcurrentRegistrationSameUsername(t *testing.T) {
|
||||
store, _ := newTestAuthStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
username := "race_" + uuid.NewString()[:8]
|
||||
const workers = 10
|
||||
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, workers)
|
||||
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
|
||||
user := model.User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: "Race Test",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
results <- store.CreateUser(ctx, user, "test_password_hash")
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
successes := 0
|
||||
conflicts := 0
|
||||
|
||||
for err := range results {
|
||||
switch {
|
||||
case err == nil:
|
||||
successes++
|
||||
case errors.Is(err, ErrUsernameTaken):
|
||||
conflicts++
|
||||
default:
|
||||
t.Fatalf("unexpected registration error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if successes != 1 || conflicts != workers-1 {
|
||||
t.Fatalf(
|
||||
"expected 1 success and %d conflicts, got %d successes and %d conflicts",
|
||||
workers-1, successes, conflicts,
|
||||
)
|
||||
}
|
||||
|
||||
t.Logf("PASS: %d successful registration, %d conflicts",
|
||||
successes, conflicts)
|
||||
}
|
||||
|
||||
func TestCreateChatRollbackOnInvalidMember(t *testing.T) {
|
||||
authStore, validUserID := newTestAuthStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
chatID := uuid.New()
|
||||
|
||||
chat := model.Chat{
|
||||
ID: chatID,
|
||||
Title: "Rollback Test",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
MemberIDs: []uuid.UUID{
|
||||
validUserID,
|
||||
uuid.New(),
|
||||
},
|
||||
}
|
||||
|
||||
err := NewChatStore(authStore.pool).CreateChat(ctx, chat)
|
||||
|
||||
if !errors.Is(err, ErrInvalidMember) {
|
||||
t.Fatalf("expected ErrInvalidMember, got %v", err)
|
||||
}
|
||||
|
||||
var chatCount int
|
||||
err = authStore.pool.QueryRow(
|
||||
ctx,
|
||||
"SELECT COUNT(*) FROM chats WHERE id = $1",
|
||||
chatID,
|
||||
).Scan(&chatCount)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("check chat existence: %v", err)
|
||||
}
|
||||
|
||||
if chatCount != 0 {
|
||||
t.Fatalf("rollback failed: chat still exists")
|
||||
}
|
||||
|
||||
var memberCount int
|
||||
err = authStore.pool.QueryRow(
|
||||
ctx,
|
||||
"SELECT COUNT(*) FROM chat_members WHERE chat_id = $1",
|
||||
chatID,
|
||||
).Scan(&memberCount)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("check chat members: %v", err)
|
||||
}
|
||||
|
||||
if memberCount != 0 {
|
||||
t.Fatalf("rollback failed: %d chat members still exist", memberCount)
|
||||
}
|
||||
|
||||
t.Log("PASS: transaction rolled back chat and member inserts")
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
type MemoryStore struct {
|
||||
mu sync.RWMutex
|
||||
users map[uuid.UUID]model.User
|
||||
chats map[uuid.UUID]model.Chat
|
||||
messages map[uuid.UUID][]model.Message
|
||||
}
|
||||
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
return &MemoryStore{
|
||||
users: make(map[uuid.UUID]model.User),
|
||||
chats: make(map[uuid.UUID]model.Chat),
|
||||
messages: make(map[uuid.UUID][]model.Message),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateUser(user model.User) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, existingUser := range s.users {
|
||||
if existingUser.Username == user.Username {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
s.users[user.ID] = user
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetUserByID(id uuid.UUID) (model.User, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
user, ok := s.users[id]
|
||||
return user, ok
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateChat(chat model.Chat) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.chats[chat.ID] = chat
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChatByID(id uuid.UUID) (model.Chat, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, ok := s.chats[id]
|
||||
return chat, ok
|
||||
}
|
||||
|
||||
func (s *MemoryStore) ListChatsForUser(userID uuid.UUID) []model.Chat {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chats := make([]model.Chat, 0)
|
||||
|
||||
for _, chat := range s.chats {
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == userID {
|
||||
chats = append(chats, chat)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return chats
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateMessage(message model.Message) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.messages[message.ChatID] = append(
|
||||
s.messages[message.ChatID],
|
||||
message,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *MemoryStore) ListMessages(chatID uuid.UUID) []model.Message {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
messages := s.messages[chatID]
|
||||
|
||||
result := make([]model.Message, len(messages))
|
||||
copy(result, messages)
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
var ErrMessageMemberNotFound = errors.New("sender is not a chat member")
|
||||
|
||||
type MessageStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageStore(pool *pgxpool.Pool) *MessageStore {
|
||||
return &MessageStore{pool: pool}
|
||||
}
|
||||
|
||||
func (s *MessageStore) CreateMessage(
|
||||
ctx context.Context,
|
||||
message model.Message,
|
||||
) error {
|
||||
const query = `
|
||||
INSERT INTO messages (
|
||||
id, chat_id, sender_id, text, created_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`
|
||||
|
||||
_, err := s.pool.Exec(ctx, query,
|
||||
message.ID,
|
||||
message.ChatID,
|
||||
message.SenderID,
|
||||
message.Text,
|
||||
message.CreatedAt,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23503" {
|
||||
return ErrMessageMemberNotFound
|
||||
}
|
||||
return fmt.Errorf("create message: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListMessages implements keyset pagination.
|
||||
// Cursor is the created_at + id of the previous page's last item.
|
||||
func (s *MessageStore) ListMessages(
|
||||
ctx context.Context,
|
||||
chatID uuid.UUID,
|
||||
limit int,
|
||||
cursorTime *time.Time,
|
||||
cursorID *uuid.UUID,
|
||||
) ([]model.Message, bool, error) {
|
||||
var rows pgx.Rows
|
||||
var err error
|
||||
|
||||
if cursorTime == nil || cursorID == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2
|
||||
`, chatID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
`, chatID, *cursorTime, *cursorID, limit+1)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
messages := make([]model.Message, 0, limit+1)
|
||||
|
||||
for rows.Next() {
|
||||
var message model.Message
|
||||
|
||||
if err := rows.Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, false, fmt.Errorf("scan message: %w", err)
|
||||
}
|
||||
|
||||
message.AttachmentIDs, err = s.attachmentIDs(ctx, message.ID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
messages = append(messages, message)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, fmt.Errorf("iterate messages: %w", err)
|
||||
}
|
||||
|
||||
hasMore := len(messages) > limit
|
||||
if hasMore {
|
||||
messages = messages[:limit]
|
||||
}
|
||||
|
||||
return messages, hasMore, nil
|
||||
}
|
||||
|
||||
var ErrIdempotencyConflict = errors.New("idempotency key reused with different message")
|
||||
|
||||
// CreateMessageIdempotent stores both the message and its deduplication record
|
||||
// in one PostgreSQL transaction. The unique constraint serializes concurrent
|
||||
// attempts across independent API processes. A rollback records neither.
|
||||
func (s *MessageStore) CreateMessageIdempotent(ctx context.Context, message model.Message, key string) (model.Message, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("begin idempotent message: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// Expired keys may be reused; only the exact scope is pruned here.
|
||||
_, err = tx.Exec(ctx, `DELETE FROM message_idempotency
|
||||
WHERE sender_id=$1 AND chat_id=$2 AND idem_key=$3 AND created_at < NOW() - INTERVAL '24 hours'`,
|
||||
message.SenderID, message.ChatID, key)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("expire idempotency: %w", err)
|
||||
}
|
||||
|
||||
tag, err := tx.Exec(ctx, `INSERT INTO message_idempotency
|
||||
(sender_id, chat_id, idem_key, text, message_id)
|
||||
VALUES ($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING`,
|
||||
message.SenderID, message.ChatID, key, messageFingerprint(message), message.ID)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("reserve idempotency: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
var existingText string
|
||||
var existingID uuid.UUID
|
||||
err = tx.QueryRow(ctx, `SELECT text, message_id FROM message_idempotency
|
||||
WHERE sender_id=$1 AND chat_id=$2 AND idem_key=$3`,
|
||||
message.SenderID, message.ChatID, key).Scan(&existingText, &existingID)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("lookup idempotency: %w", err)
|
||||
}
|
||||
if existingText != messageFingerprint(message) {
|
||||
return model.Message{}, ErrIdempotencyConflict
|
||||
}
|
||||
var original model.Message
|
||||
err = tx.QueryRow(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE id=$1`, existingID).
|
||||
Scan(&original.ID, &original.ChatID, &original.SenderID, &original.Text, &original.CreatedAt)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("read idempotent message: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
original.AttachmentIDs, err = s.attachmentIDs(ctx, original.ID)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
return original, nil
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `INSERT INTO messages (id,chat_id,sender_id,text,created_at)
|
||||
VALUES ($1,$2,$3,$4,$5)`, message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23503" {
|
||||
return model.Message{}, ErrMessageMemberNotFound
|
||||
}
|
||||
return model.Message{}, fmt.Errorf("insert idempotent message: %w", err)
|
||||
}
|
||||
if err := s.linkAttachments(ctx, tx, message); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, fmt.Errorf("commit idempotent message: %w", err)
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *MessageStore) attachmentIDs(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) {
|
||||
rows, err := s.pool.Query(ctx, `SELECT attachment_id FROM message_attachments WHERE message_id=$1 ORDER BY attachment_id`, messageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := make([]uuid.UUID, 0)
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err = rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
}
|
||||
func (s *MessageStore) linkAttachments(ctx context.Context, tx pgx.Tx, m model.Message) error {
|
||||
for _, id := range m.AttachmentIDs {
|
||||
tag, err := tx.Exec(ctx, `INSERT INTO message_attachments(message_id,attachment_id)
|
||||
SELECT $1,a.id FROM attachments a WHERE a.id=$2 AND a.chat_id=$3`, m.ID, id, m.ChatID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return ErrAttachmentNotFound
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var ErrAttachmentNotFound = errors.New("attachment not found in chat")
|
||||
|
||||
func messageFingerprint(m model.Message) string {
|
||||
ids := append([]uuid.UUID(nil), m.AttachmentIDs...)
|
||||
sort.Slice(ids, func(i, j int) bool { return ids[i].String() < ids[j].String() })
|
||||
b, _ := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
IDs []uuid.UUID `json:"attachment_ids"`
|
||||
}{m.Text, ids})
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/migrations"
|
||||
)
|
||||
|
||||
func ApplyMigrations(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin migrations: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// Serialize migrations across API instances.
|
||||
_, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(20260002)`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lock migrations: %w", err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version BIGINT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create migration history: %w", err)
|
||||
}
|
||||
|
||||
entries, err := fs.ReadDir(migrations.Files, ".")
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migrations: %w", err)
|
||||
}
|
||||
|
||||
names := make([]string, 0)
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".up.sql") {
|
||||
names = append(names, entry.Name())
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
for _, name := range names {
|
||||
versionPart := strings.SplitN(name, "_", 2)[0]
|
||||
|
||||
version, err := strconv.ParseInt(versionPart, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid migration filename %q: %w", name, err)
|
||||
}
|
||||
|
||||
var applied bool
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM schema_migrations
|
||||
WHERE version = $1
|
||||
)
|
||||
`, version).Scan(&applied)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check migration %d: %w", version, err)
|
||||
}
|
||||
|
||||
if applied {
|
||||
continue
|
||||
}
|
||||
|
||||
sql, err := fs.ReadFile(migrations.Files, name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migration %s: %w", name, err)
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, string(sql)); err != nil {
|
||||
return fmt.Errorf("apply migration %s: %w", name, err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO schema_migrations (version)
|
||||
VALUES ($1)
|
||||
`, version)
|
||||
if err != nil {
|
||||
return fmt.Errorf("record migration %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit migrations: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func NewPostgresPool(
|
||||
ctx context.Context,
|
||||
databaseURL string,
|
||||
) (*pgxpool.Pool, error) {
|
||||
config, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"invalid database config: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
config.MaxConns = 10
|
||||
config.MinConns = 1
|
||||
config.MaxConnLifetime = 30 * time.Minute
|
||||
config.MaxConnIdleTime = 5 * time.Minute
|
||||
config.HealthCheckPeriod = time.Minute
|
||||
config.ConnConfig.ConnectTimeout = 5 * time.Second
|
||||
|
||||
connectCtx, cancel := context.WithTimeout(
|
||||
ctx,
|
||||
10*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(
|
||||
connectCtx,
|
||||
config,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"create postgres pool: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if err := pool.Ping(connectCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf(
|
||||
"postgres unavailable: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// S3Client uses AWS Signature V4 with path-style requests (MinIO-compatible).
|
||||
// No credentials or bucket identifiers are returned through the public API.
|
||||
type S3Client struct {
|
||||
Endpoint, Region, Bucket, Key, Secret string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
func NewS3Client() (*S3Client, error) {
|
||||
s := &S3Client{Endpoint: strings.TrimRight(os.Getenv("S3_ENDPOINT"), "/"), Region: os.Getenv("S3_REGION"), Bucket: os.Getenv("S3_BUCKET"), Key: os.Getenv("S3_ACCESS_KEY_ID"), Secret: os.Getenv("S3_SECRET_ACCESS_KEY"), HTTP: &http.Client{Timeout: 12 * time.Second}}
|
||||
if s.Region == "" {
|
||||
s.Region = "us-east-1"
|
||||
}
|
||||
if s.Endpoint == "" || s.Bucket == "" || s.Key == "" || s.Secret == "" {
|
||||
return nil, errors.New("missing S3 configuration")
|
||||
}
|
||||
u, err := url.Parse(s.Endpoint)
|
||||
if err != nil || u.Scheme != "http" && u.Scheme != "https" || u.Host == "" {
|
||||
return nil, errors.New("invalid S3 endpoint")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
func mac(key []byte, value string) []byte {
|
||||
m := hmac.New(sha256.New, key)
|
||||
m.Write([]byte(value))
|
||||
return m.Sum(nil)
|
||||
}
|
||||
func hexsum(data []byte) string { v := sha256.Sum256(data); return hex.EncodeToString(v[:]) }
|
||||
func (s *S3Client) request(ctx context.Context, method, key, contentType string, body []byte) ([]byte, error) {
|
||||
path := "/" + s.Bucket
|
||||
if key != "" {
|
||||
path += "/" + strings.ReplaceAll(url.PathEscape(key), "%2F", "/")
|
||||
}
|
||||
endpoint, err := url.Parse(s.Endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
target := s.Endpoint + path
|
||||
req, err := http.NewRequestWithContext(ctx, method, target, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
date := now.Format("20060102")
|
||||
amzDate := now.Format("20060102T150405Z")
|
||||
digest := hexsum(body)
|
||||
req.Header.Set("x-amz-date", amzDate)
|
||||
req.Header.Set("x-amz-content-sha256", digest)
|
||||
if contentType != "" {
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
canonicalHeaders := "host:" + endpoint.Host + "\n" + "x-amz-content-sha256:" + digest + "\n" + "x-amz-date:" + amzDate + "\n"
|
||||
signedHeaders := "host;x-amz-content-sha256;x-amz-date"
|
||||
canonical := method + "\n" + path + "\n\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + digest
|
||||
scope := date + "/" + s.Region + "/s3/aws4_request"
|
||||
toSign := "AWS4-HMAC-SHA256\n" + amzDate + "\n" + scope + "\n" + hexsum([]byte(canonical))
|
||||
signingKey := mac(mac(mac(mac([]byte("AWS4"+s.Secret), date), s.Region), "s3"), "aws4_request")
|
||||
auth := "AWS4-HMAC-SHA256 Credential=" + s.Key + "/" + scope + ", SignedHeaders=" + signedHeaders + ", Signature=" + hex.EncodeToString(mac(signingKey, toSign))
|
||||
req.Header.Set("Authorization", auth)
|
||||
resp, err := s.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
return nil, fmt.Errorf("S3 returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
return io.ReadAll(io.LimitReader(resp.Body, 10*1024*1024+1))
|
||||
}
|
||||
func (s *S3Client) Put(ctx context.Context, key, mime string, body []byte) error {
|
||||
_, err := s.request(ctx, "PUT", key, mime, body)
|
||||
return err
|
||||
}
|
||||
func (s *S3Client) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
return s.request(ctx, "GET", key, "", nil)
|
||||
}
|
||||
func (s *S3Client) Delete(ctx context.Context, key string) error {
|
||||
_, err := s.request(ctx, "DELETE", key, "", nil)
|
||||
return err
|
||||
}
|
||||
func (s *S3Client) Ready(ctx context.Context) error {
|
||||
_, err := s.request(ctx, "HEAD", "", "", nil)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type SessionCache struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionCache(redisURL string) (*SessionCache, error) {
|
||||
options, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid redis URL: %w", err)
|
||||
}
|
||||
|
||||
options.DialTimeout = 2 * time.Second
|
||||
options.ReadTimeout = 2 * time.Second
|
||||
options.WriteTimeout = 2 * time.Second
|
||||
options.MaxRetries = 0
|
||||
|
||||
return &SessionCache{
|
||||
client: redis.NewClient(options),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *SessionCache) Close() error {
|
||||
return c.client.Close()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Ping(ctx context.Context) error {
|
||||
return c.client.Ping(ctx).Err()
|
||||
}
|
||||
|
||||
func cacheKey(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "session:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (c *SessionCache) Set(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
user model.User,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
ttl := time.Until(expiresAt)
|
||||
if ttl <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.client.Set(ctx, cacheKey(token), payload, ttl).Err()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Get(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (model.User, bool, error) {
|
||||
value, err := c.client.Get(ctx, cacheKey(token)).Result()
|
||||
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return model.User{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
|
||||
var user model.User
|
||||
if err := json.Unmarshal([]byte(value), &user); err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
return user, true, nil
|
||||
}
|
||||
|
||||
func (c *SessionCache) Delete(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
return c.client.Del(ctx, cacheKey(token)).Err()
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
type SessionService struct {
|
||||
db *AuthStore
|
||||
cache *SessionCache
|
||||
}
|
||||
|
||||
func NewSessionService(
|
||||
db *AuthStore,
|
||||
cache *SessionCache,
|
||||
) *SessionService {
|
||||
return &SessionService{
|
||||
db: db,
|
||||
cache: cache,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SessionService) CreateSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
userID uuid.UUID,
|
||||
createdAt time.Time,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
if err := s.db.CreateSession(
|
||||
ctx, token, userID, createdAt, expiresAt,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Populate the profile cache best-effort after the authoritative INSERT.
|
||||
if s.cache != nil {
|
||||
user, err := s.db.GetUserByID(ctx, userID)
|
||||
if err == nil {
|
||||
cacheCtx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
|
||||
_ = s.cache.Set(cacheCtx, token, user, expiresAt)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SessionService) GetSessionUser(ctx context.Context, token string) (model.User, error) {
|
||||
// A cheap indexed PostgreSQL check on EVERY request enforces expiry and logout,
|
||||
// even if Redis contains a stale value or its deletion fails.
|
||||
userID, err := s.db.GetActiveSessionUserID(ctx, token)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
cached, hit, err := s.cache.Get(cacheCtx, token)
|
||||
cancel()
|
||||
if err == nil && hit && cached.ID == userID {
|
||||
return cached, nil
|
||||
}
|
||||
}
|
||||
user, err := s.db.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
// Conservative short TTL on read-through; session lifetime is still checked in PostgreSQL.
|
||||
_ = s.cache.Set(cacheCtx, token, user, time.Now().Add(30*time.Second))
|
||||
cancel()
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *SessionService) RevokeSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
if err := s.db.RevokeSession(ctx, token); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(
|
||||
context.Background(), 250*time.Millisecond,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
_ = s.cache.Delete(cacheCtx, token)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
func newTestAuthStore(t *testing.T) (*AuthStore, uuid.UUID) {
|
||||
t.Helper()
|
||||
|
||||
databaseURL := os.Getenv("TEST_DATABASE_URL")
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set; integration test skipped")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
pool, err := NewPostgresPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
t.Fatalf("connect to PostgreSQL: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
|
||||
store := NewAuthStore(pool)
|
||||
|
||||
userID := uuid.New()
|
||||
username := "test_" + uuid.NewString()[:8]
|
||||
|
||||
user := model.User{
|
||||
ID: userID,
|
||||
Username: username,
|
||||
DisplayName: "Integration Test",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
err = store.CreateUser(ctx, user, "test-password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("create test user: %v", err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, _ = pool.Exec(cleanupCtx,
|
||||
"DELETE FROM sessions WHERE user_id = $1", userID)
|
||||
_, _ = pool.Exec(cleanupCtx,
|
||||
"DELETE FROM users WHERE id = $1", userID)
|
||||
})
|
||||
|
||||
return store, userID
|
||||
}
|
||||
|
||||
func TestSessionCreateAndGet(t *testing.T) {
|
||||
store, userID := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
token := "test-token-" + uuid.NewString()
|
||||
|
||||
err := service.CreateSession(
|
||||
ctx, token, userID, now, now.Add(time.Hour),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
|
||||
user, err := service.GetSessionUser(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatalf("get session user: %v", err)
|
||||
}
|
||||
|
||||
if user.ID != userID {
|
||||
t.Fatalf("expected user %s, got %s", userID, user.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiredSessionRejected(t *testing.T) {
|
||||
store, userID := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
token := "expired-token-" + uuid.NewString()
|
||||
|
||||
err := service.CreateSession(
|
||||
ctx,
|
||||
token,
|
||||
userID,
|
||||
now.Add(-2*time.Hour),
|
||||
now.Add(-time.Hour),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create expired session: %v", err)
|
||||
}
|
||||
|
||||
_, err = service.GetSessionUser(ctx, token)
|
||||
|
||||
if !errors.Is(err, ErrSessionNotFound) {
|
||||
t.Fatalf("expected ErrSessionNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogoutRevokesSession(t *testing.T) {
|
||||
store, userID := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
token := "logout-token-" + uuid.NewString()
|
||||
|
||||
err := service.CreateSession(
|
||||
ctx, token, userID, now, now.Add(time.Hour),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
|
||||
err = service.RevokeSession(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatalf("revoke session: %v", err)
|
||||
}
|
||||
|
||||
_, err = service.GetSessionUser(ctx, token)
|
||||
|
||||
if !errors.Is(err, ErrSessionNotFound) {
|
||||
t.Fatalf("expected revoked token to be rejected, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownTokenRejected(t *testing.T) {
|
||||
store, _ := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
token := fmt.Sprintf("unknown-%s", uuid.NewString())
|
||||
|
||||
_, err := service.GetSessionUser(context.Background(), token)
|
||||
|
||||
if !errors.Is(err, ErrSessionNotFound) {
|
||||
t.Fatalf("expected ErrSessionNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user