lab2: postgres, sessions, redis, persistence, stale read
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
Env string
|
||||
SessionTTLSeconds int
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
SessionStore string
|
||||
LogLevel slog.Level
|
||||
ShutdownTimeout time.Duration
|
||||
}
|
||||
|
||||
func Load() Config {
|
||||
return Config{
|
||||
Host: getEnv("APP_HOST", "0.0.0.0"),
|
||||
Port: getEnv("APP_PORT", "8080"),
|
||||
Env: getEnv("APP_ENV", "lab"),
|
||||
SessionTTLSeconds: getInt("SESSION_TTL_SECONDS", 3600),
|
||||
DatabaseURL: readSecretFile("DATABASE_URL_FILE"),
|
||||
CacheURL: readSecretFile("CACHE_URL_FILE"),
|
||||
SessionStore: getEnv("SESSION_STORE", "postgres"),
|
||||
LogLevel: parseLevel(getEnv("LOG_LEVEL", "info")),
|
||||
ShutdownTimeout: parseDuration(getEnv("SHUTDOWN_TIMEOUT", "8s")),
|
||||
}
|
||||
}
|
||||
|
||||
func (c Config) SessionTTL() time.Duration {
|
||||
return time.Duration(c.SessionTTLSeconds) * time.Second
|
||||
}
|
||||
|
||||
func (c Config) Addr() string { return c.Host + ":" + c.Port }
|
||||
|
||||
func getEnv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func getInt(key string, def int) int {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func readSecretFile(envKey string) string {
|
||||
path := os.Getenv(envKey)
|
||||
if path == "" {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
slog.Warn("secret file not readable", "path", path, "err", err)
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
func parseLevel(s string) slog.Level {
|
||||
var l slog.Level
|
||||
if err := l.UnmarshalText([]byte(s)); err != nil {
|
||||
return slog.LevelInfo
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func parseDuration(s string) time.Duration {
|
||||
d, err := time.ParseDuration(s)
|
||||
if err != nil {
|
||||
return 8 * time.Second
|
||||
}
|
||||
return d
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (c Chat) MarshalJSON() ([]byte, error) {
|
||||
type Alias Chat
|
||||
members := c.MemberIDs
|
||||
if members == nil {
|
||||
members = []string{}
|
||||
}
|
||||
return json.Marshal(&struct {
|
||||
Alias
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}{
|
||||
Alias: Alias(c),
|
||||
MemberIDs: members,
|
||||
CreatedAt: c.CreatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (m Message) MarshalJSON() ([]byte, error) {
|
||||
type Alias Message
|
||||
return json.Marshal(&struct {
|
||||
Alias
|
||||
CreatedAt string `json:"created_at"`
|
||||
}{
|
||||
Alias: Alias(m),
|
||||
CreatedAt: m.CreatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
UserID string `json:"-"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `json:"-"`
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// MarshalJSON форматирует CreatedAt в RFC3339 без микросекунд.
|
||||
func (u User) MarshalJSON() ([]byte, error) {
|
||||
type Alias User
|
||||
return json.Marshal(&struct {
|
||||
Alias
|
||||
CreatedAt string `json:"created_at"`
|
||||
}{
|
||||
Alias: Alias(u),
|
||||
CreatedAt: u.CreatedAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
)
|
||||
|
||||
type ChatRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatRepository(pool *pgxpool.Pool) *ChatRepository {
|
||||
return &ChatRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *ChatRepository) Create(ctx context.Context, chat *domain.Chat) error {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
const insertChat = `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`
|
||||
if _, err := tx.Exec(ctx, insertChat, chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
const insertMember = `INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`
|
||||
for _, uid := range chat.MemberIDs {
|
||||
if _, err := tx.Exec(ctx, insertMember, chat.ID, uid); err != nil {
|
||||
return fmt.Errorf("insert member %s: %w", uid, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetByID(ctx context.Context, id string) (*domain.Chat, error) {
|
||||
const q = `SELECT id, title, created_at FROM chats WHERE id = $1::uuid`
|
||||
var c domain.Chat
|
||||
err := r.pool.QueryRow(ctx, q, id).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select chat: %w", err)
|
||||
}
|
||||
|
||||
const qMembers = `SELECT user_id FROM chat_members WHERE chat_id = $1::uuid ORDER BY user_id`
|
||||
rows, err := r.pool.Query(ctx, qMembers, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select members: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
c.MemberIDs = []string{}
|
||||
for rows.Next() {
|
||||
var uid string
|
||||
if err := rows.Scan(&uid); err != nil {
|
||||
return nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
c.MemberIDs = append(c.MemberIDs, uid)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate members: %w", err)
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) IsMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
const q = `SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid`
|
||||
var one int
|
||||
err := r.pool.QueryRow(ctx, q, chatID, userID).Scan(&one)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
const qChat = `SELECT 1 FROM chats WHERE id = $1::uuid`
|
||||
err = r.pool.QueryRow(ctx, qChat, chatID).Scan(&one)
|
||||
if err == nil {
|
||||
return false, nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, repository.ErrNotFound
|
||||
}
|
||||
return false, fmt.Errorf("check chat exists: %w", err)
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListByMember(ctx context.Context, userID string, cursor time.Time, cursorID string, limit int) ([]*domain.Chat, error) {
|
||||
const qChats = `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1::uuid
|
||||
AND (c.created_at > $2 OR (c.created_at = $2 AND c.id > $3::uuid))
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, qChats, userID, cursor, cursorID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
chats := []*domain.Chat{}
|
||||
var chatIDs []string
|
||||
for rows.Next() {
|
||||
var c domain.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("scan chat: %w", err)
|
||||
}
|
||||
c.MemberIDs = []string{}
|
||||
chats = append(chats, &c)
|
||||
chatIDs = append(chatIDs, c.ID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate chats: %w", err)
|
||||
}
|
||||
if len(chats) == 0 {
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
const qMembers = `
|
||||
SELECT chat_id, user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = ANY($1::uuid[])
|
||||
ORDER BY chat_id, user_id
|
||||
`
|
||||
memberRows, err := r.pool.Query(ctx, qMembers, chatIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list members: %w", err)
|
||||
}
|
||||
defer memberRows.Close()
|
||||
|
||||
byChat := make(map[string][]string)
|
||||
for memberRows.Next() {
|
||||
var chatID, uid string
|
||||
if err := memberRows.Scan(&chatID, &uid); err != nil {
|
||||
return nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
byChat[chatID] = append(byChat[chatID], uid)
|
||||
}
|
||||
if err := memberRows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate members: %w", err)
|
||||
}
|
||||
for _, c := range chats {
|
||||
if members, ok := byChat[c.ID]; ok {
|
||||
c.MemberIDs = members
|
||||
}
|
||||
}
|
||||
return chats, nil
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageRepository(pool *pgxpool.Pool) *MessageRepository {
|
||||
return &MessageRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessageRepository) Create(ctx context.Context, msg *domain.Message) error {
|
||||
const q = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2::uuid, $3::uuid, $4, $5)
|
||||
`
|
||||
if _, err := r.pool.Exec(ctx, q, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error) {
|
||||
const q = `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1::uuid
|
||||
AND (created_at > $2 OR (created_at = $2 AND id > $3::uuid))
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, chatID, cursor, cursorID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
msgs := []*domain.Message{}
|
||||
for rows.Next() {
|
||||
var m domain.Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("scan message: %w", err)
|
||||
}
|
||||
msgs = append(msgs, &m)
|
||||
}
|
||||
return msgs, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// NewPool создаёт пул соединений с PostgreSQL.
|
||||
// Параметры ограничены, чтобы не перегрузить БД.
|
||||
func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
|
||||
cfg.MaxConns = 20
|
||||
cfg.MinConns = 2
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.HealthCheckPeriod = 30 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
// Проверяем, что соединение работает.
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
)
|
||||
|
||||
type SessionRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewSessionRepository(pool *pgxpool.Pool) *SessionRepository {
|
||||
return &SessionRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Create(ctx context.Context, s *domain.Session) error {
|
||||
const q = `INSERT INTO sessions (token, user_id, expires_at, created_at) VALUES ($1, $2, $3, $4)`
|
||||
if _, err := r.pool.Exec(ctx, q, s.Token, s.UserID, s.ExpiresAt, s.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) GetByToken(ctx context.Context, token string) (*domain.Session, error) {
|
||||
const q = `SELECT token, user_id, expires_at, created_at FROM sessions WHERE token = $1`
|
||||
var s domain.Session
|
||||
err := r.pool.QueryRow(ctx, q, token).Scan(&s.Token, &s.UserID, &s.ExpiresAt, &s.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select session: %w", err)
|
||||
}
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Delete(ctx context.Context, token string) error {
|
||||
const q = `DELETE FROM sessions WHERE token = $1`
|
||||
if _, err := r.pool.Exec(ctx, q, token); err != nil {
|
||||
return fmt.Errorf("delete session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) DeleteExpired(ctx context.Context) error {
|
||||
const q = `DELETE FROM sessions WHERE expires_at < now()`
|
||||
if _, err := r.pool.Exec(ctx, q); err != nil {
|
||||
return fmt.Errorf("delete expired: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRepository(pool *pgxpool.Pool) *UserRepository {
|
||||
return &UserRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, user *domain.User, passwordHash string) error {
|
||||
const q = `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, user.ID, user.Username, user.DisplayName, passwordHash, user.CreatedAt)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation
|
||||
return repository.ErrConflict
|
||||
}
|
||||
return fmt.Errorf("insert user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
const q = `
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`
|
||||
var u domain.User
|
||||
err := r.pool.QueryRow(ctx, q, id).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select user by id: %w", err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
|
||||
const q = `
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
var u domain.User
|
||||
err := r.pool.QueryRow(ctx, q, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("select user by username: %w", err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetPasswordHash(ctx context.Context, userID string) (string, error) {
|
||||
const q = `SELECT password_hash FROM users WHERE id = $1`
|
||||
var hash string
|
||||
err := r.pool.QueryRow(ctx, q, userID).Scan(&hash)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", repository.ErrNotFound
|
||||
}
|
||||
return "", fmt.Errorf("select password hash: %w", err)
|
||||
}
|
||||
return hash, nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
type MessageCache struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewMessageCache(client *redis.Client) *MessageCache {
|
||||
return &MessageCache{client: client}
|
||||
}
|
||||
|
||||
func (c *MessageCache) Get(ctx context.Context, chatID, cursor string) ([]*domain.Message, bool) {
|
||||
key := fmt.Sprintf("messages:%s:%s", chatID, cursor)
|
||||
raw, err := c.client.Get(ctx, key).Bytes()
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
var msgs []*domain.Message
|
||||
if err := json.Unmarshal(raw, &msgs); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return msgs, true
|
||||
}
|
||||
|
||||
func (c *MessageCache) Set(ctx context.Context, chatID, cursor string, msgs []*domain.Message) {
|
||||
key := fmt.Sprintf("messages:%s:%s", chatID, cursor)
|
||||
raw, _ := json.Marshal(msgs)
|
||||
_ = c.client.Set(ctx, key, raw, 30*time.Second).Err()
|
||||
}
|
||||
|
||||
func (c *MessageCache) Invalidate(ctx context.Context, chatID string) error {
|
||||
pattern := fmt.Sprintf("messages:%s:*", chatID)
|
||||
keys, err := c.client.Keys(ctx, pattern).Result()
|
||||
if err != nil || len(keys) == 0 {
|
||||
return err
|
||||
}
|
||||
return c.client.Del(ctx, keys...).Err()
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
)
|
||||
|
||||
type SessionRepository struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionRepository(client *redis.Client) *SessionRepository {
|
||||
return &SessionRepository{client: client}
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Create(ctx context.Context, s *domain.Session) error {
|
||||
key := "session:" + s.Token
|
||||
ttl := time.Until(s.ExpiresAt)
|
||||
if ttl <= 0 {
|
||||
return fmt.Errorf("session already expired")
|
||||
}
|
||||
if err := r.client.Set(ctx, key, s.UserID, ttl).Err(); err != nil {
|
||||
return fmt.Errorf("set session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) GetByToken(ctx context.Context, token string) (*domain.Session, error) {
|
||||
key := "session:" + token
|
||||
userID, err := r.client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get session: %w", err)
|
||||
}
|
||||
ttl, err := r.client.TTL(ctx, key).Result()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ttl: %w", err)
|
||||
}
|
||||
return &domain.Session{
|
||||
Token: token,
|
||||
UserID: userID,
|
||||
ExpiresAt: time.Now().UTC().Add(ttl),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Delete(ctx context.Context, token string) error {
|
||||
return r.client.Del(ctx, "session:"+token).Err()
|
||||
}
|
||||
|
||||
func (r *SessionRepository) DeleteExpired(ctx context.Context) error {
|
||||
// Redis TTL сам удаляет истёкшие; no-op.
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, url string) (*redis.Client, error) {
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse redis url: %w", err)
|
||||
}
|
||||
client := redis.NewClient(opts)
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
return nil, fmt.Errorf("ping redis: %w", err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
var ErrNotFound = errNotFound{}
|
||||
|
||||
type errNotFound struct{}
|
||||
|
||||
func (errNotFound) Error() string { return "not found" }
|
||||
|
||||
var ErrConflict = errConflict{}
|
||||
|
||||
type errConflict struct{}
|
||||
|
||||
func (errConflict) Error() string { return "conflict" }
|
||||
|
||||
// UserRepository
|
||||
type UserRepository interface {
|
||||
Create(ctx context.Context, user *domain.User, passwordHash string) error
|
||||
GetByID(ctx context.Context, id string) (*domain.User, error)
|
||||
GetByUsername(ctx context.Context, username string) (*domain.User, error)
|
||||
GetPasswordHash(ctx context.Context, userID string) (string, error)
|
||||
}
|
||||
|
||||
// ChatRepository
|
||||
type ChatRepository interface {
|
||||
Create(ctx context.Context, chat *domain.Chat) error
|
||||
GetByID(ctx context.Context, id string) (*domain.Chat, error)
|
||||
IsMember(ctx context.Context, chatID, userID string) (bool, error)
|
||||
ListByMember(ctx context.Context, userID string, cursor time.Time, cursorID string, limit int) ([]*domain.Chat, error)
|
||||
}
|
||||
|
||||
// MessageRepository
|
||||
type MessageRepository interface {
|
||||
Create(ctx context.Context, msg *domain.Message) error
|
||||
ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error)
|
||||
}
|
||||
|
||||
// SessionRepository
|
||||
type SessionRepository interface {
|
||||
Create(ctx context.Context, s *domain.Session) error
|
||||
GetByToken(ctx context.Context, token string) (*domain.Session, error)
|
||||
Delete(ctx context.Context, token string) error
|
||||
DeleteExpired(ctx context.Context) error
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
users repository.UserRepository
|
||||
sessions repository.SessionRepository
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewAuthService(users repository.UserRepository, sessions repository.SessionRepository, ttl time.Duration) *AuthService {
|
||||
return &AuthService{users: users, sessions: sessions, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *AuthService) Login(ctx context.Context, username, password string) (*domain.Session, *domain.User, error) {
|
||||
u, err := s.users.GetByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
_, _ = hashPassword("dummy-password-for-timing")
|
||||
return nil, nil, ErrUnauthorized
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
hash, err := s.users.GetPasswordHash(ctx, u.ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if err := verifyPassword(password, hash); err != nil {
|
||||
if errors.Is(err, ErrPasswordMismatch) {
|
||||
return nil, nil, ErrUnauthorized
|
||||
}
|
||||
return nil, nil, fmt.Errorf("verify password: %w", err)
|
||||
}
|
||||
|
||||
token, err := generateToken()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
|
||||
now := nowUTC()
|
||||
sess := &domain.Session{
|
||||
Token: token,
|
||||
UserID: u.ID,
|
||||
ExpiresAt: now.Add(s.ttl),
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := s.sessions.Create(ctx, sess); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return sess, u, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) ValidateSession(ctx context.Context, token string) (*domain.User, error) {
|
||||
sess, err := s.sessions.GetByToken(ctx, token)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if nowUTC().After(sess.ExpiresAt) {
|
||||
_ = s.sessions.Delete(ctx, token)
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
u, err := s.users.GetByID(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
return s.sessions.Delete(ctx, token)
|
||||
}
|
||||
|
||||
func generateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
)
|
||||
|
||||
type ChatService struct {
|
||||
chats repository.ChatRepository
|
||||
users repository.UserRepository
|
||||
}
|
||||
|
||||
func NewChatService(chats repository.ChatRepository, users repository.UserRepository) *ChatService {
|
||||
return &ChatService{chats: chats, users: users}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, callerID, title string, memberIDs []string) (*domain.Chat, error) {
|
||||
if !validateTitle(title) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
callerFound := false
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == callerID {
|
||||
callerFound = true
|
||||
}
|
||||
}
|
||||
if !callerFound {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
for id := range seen {
|
||||
if _, err := s.users.GetByID(ctx, id); err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
c := &domain.Chat{
|
||||
ID: newID(),
|
||||
Title: title,
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.chats.Create(ctx, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(ctx context.Context, callerID, chatID string) (*domain.Chat, error) {
|
||||
ok, err := s.chats.IsMember(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
c, err := s.chats.GetByID(ctx, chatID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) List(ctx context.Context, callerID, cursor string, limit int) ([]*domain.Chat, string, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
|
||||
cursorTime := time.Unix(0, 0).UTC()
|
||||
cursorID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != "" {
|
||||
t, id, err := decodeCursor(cursor, callerID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
cursorTime, cursorID = t, id
|
||||
}
|
||||
|
||||
items, err := s.chats.ListByMember(ctx, callerID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if items == nil {
|
||||
items = []*domain.Chat{}
|
||||
}
|
||||
|
||||
var next string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = encodeCursor(callerID, last.CreatedAt, last.ID)
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository/memory"
|
||||
)
|
||||
|
||||
type chatFixture struct {
|
||||
users *UserService
|
||||
chats *ChatService
|
||||
aliceID string
|
||||
bobID string
|
||||
carolID string
|
||||
}
|
||||
|
||||
func newChatFixture(t *testing.T) *chatFixture {
|
||||
t.Helper()
|
||||
userRepo := memory.NewUserRepository()
|
||||
chatRepo := memory.NewChatRepository()
|
||||
userSvc := NewUserService(userRepo)
|
||||
chatSvc := NewChatService(chatRepo, userRepo)
|
||||
ctx := context.Background()
|
||||
|
||||
alice, err := userSvc.Register(ctx, "alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("register alice: %v", err)
|
||||
}
|
||||
bob, err := userSvc.Register(ctx, "bob", "Боб")
|
||||
if err != nil {
|
||||
t.Fatalf("register bob: %v", err)
|
||||
}
|
||||
carol, err := userSvc.Register(ctx, "carol", "Кэрол")
|
||||
if err != nil {
|
||||
t.Fatalf("register carol: %v", err)
|
||||
}
|
||||
return &chatFixture{
|
||||
users: userSvc,
|
||||
chats: chatSvc,
|
||||
aliceID: alice.ID,
|
||||
bobID: bob.ID,
|
||||
carolID: carol.ID,
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Create_OK(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
c, err := f.chats.Create(ctx, f.aliceID, "Project", []string{f.aliceID, f.bobID})
|
||||
if err != nil {
|
||||
t.Fatalf("Create failed: %v", err)
|
||||
}
|
||||
if len(c.MemberIDs) != 2 {
|
||||
t.Errorf("expected 2 members, got %d", len(c.MemberIDs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Create_CallerNotInMembers(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// Alice создаёт чат, но в member_ids только Bob.
|
||||
_, err := f.chats.Create(ctx, f.aliceID, "Project", []string{f.bobID})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Create_UnknownMember(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := f.chats.Create(ctx, f.aliceID, "Project", []string{f.aliceID, "nonexistent-uuid"})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Create_DuplicateMembers(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := f.chats.Create(ctx, f.aliceID, "Project", []string{f.aliceID, f.aliceID})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Create_InvalidTitle(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
cases := []string{"", " "}
|
||||
for _, title := range cases {
|
||||
_, err := f.chats.Create(ctx, f.aliceID, title, []string{f.aliceID})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("title %q: expected ErrInvalidInput, got %v", title, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Get_Member(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
c, _ := f.chats.Create(ctx, f.aliceID, "Project", []string{f.aliceID, f.bobID})
|
||||
|
||||
got, err := f.chats.Get(ctx, f.bobID, c.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("Get failed: %v", err)
|
||||
}
|
||||
if got.ID != c.ID {
|
||||
t.Errorf("id mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Get_Stranger(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
c, _ := f.chats.Create(ctx, f.aliceID, "Project", []string{f.aliceID, f.bobID})
|
||||
|
||||
// Carol не член — должна получить ErrNotFound, не ErrForbidden.
|
||||
_, err := f.chats.Get(ctx, f.carolID, c.ID)
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound for stranger, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Get_Nonexistent(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := f.chats.Get(ctx, f.aliceID, "nonexistent-chat")
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_List_OnlyMemberChats(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = f.chats.Create(ctx, f.aliceID, "A-B", []string{f.aliceID, f.bobID})
|
||||
_, _ = f.chats.Create(ctx, f.aliceID, "A-C", []string{f.aliceID, f.carolID})
|
||||
_, _ = f.chats.Create(ctx, f.bobID, "B-C", []string{f.bobID, f.carolID})
|
||||
|
||||
items, _, err := f.chats.List(ctx, f.aliceID, "", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("List failed: %v", err)
|
||||
}
|
||||
if len(items) != 2 {
|
||||
t.Errorf("expected 2 chats for alice, got %d", len(items))
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_List_InvalidLimit(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
for _, limit := range []int{0, -1, 101} {
|
||||
_, _, err := f.chats.List(ctx, f.aliceID, "", limit)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("limit %d: expected ErrInvalidInput, got %v", limit, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_List_InvalidCursor(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _, err := f.chats.List(ctx, f.aliceID, "!!!bad-cursor!!!", 10)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// encodeCursor кодирует (scope, created_at, id) в base64.
|
||||
func encodeCursor(scope string, createdAt time.Time, id string) string {
|
||||
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
// decodeCursor декодирует и проверяет scope.
|
||||
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
parts := strings.SplitN(string(raw), "|", 3)
|
||||
if len(parts) != 3 || parts[0] != expectedScope {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
return t, parts[2], nil
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package service
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
// ErrInvalidInput — невалидные данные от клиента (не проходит валидацию).
|
||||
// Мапится в HTTP 400 invalid_request.
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
|
||||
// ErrUnauthorized — нет аутентификации или она недействительна.
|
||||
// Мапится в HTTP 401 unauthorized.
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
|
||||
// ErrNotFound — объект не существует или недоступен вызывающему.
|
||||
// README требует: чужой объект → 404, чтобы не раскрывать существование.
|
||||
// Мапится в HTTP 404 not_found.
|
||||
ErrNotFound = errors.New("not found")
|
||||
|
||||
// ErrConflict — нарушение уникальности (занятый username).
|
||||
// Мапится в HTTP 409 conflict.
|
||||
ErrConflict = errors.New("conflict")
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
|
||||
}
|
||||
|
||||
// nowUTC возвращает время UTC с точностью до секунд.
|
||||
// PostgreSQL и Python-клиент тестов ожидают формат без наносекунд.
|
||||
func nowUTC() time.Time {
|
||||
return time.Now().UTC().Truncate(time.Second)
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
redisrepo "github.com/charawein/mtusi2026lab2/internal/repository/redis"
|
||||
)
|
||||
|
||||
type MessageService struct {
|
||||
messages repository.MessageRepository
|
||||
chats repository.ChatRepository
|
||||
cache *redisrepo.MessageCache
|
||||
invalidate bool // ВРЕМЕННЫЙ ФЛАГ для демонстрации stale read
|
||||
}
|
||||
|
||||
func NewMessageService(messages repository.MessageRepository, chats repository.ChatRepository, cache *redisrepo.MessageCache) *MessageService {
|
||||
return &MessageService{messages: messages, chats: chats, cache: cache, invalidate: false}
|
||||
}
|
||||
|
||||
func (s *MessageService) SetInvalidate(v bool) { s.invalidate = v }
|
||||
|
||||
func (s *MessageService) Send(ctx context.Context, senderID, chatID, text string) (*domain.Message, error) {
|
||||
if !validateText(text) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
ok, err := s.chats.IsMember(ctx, chatID, senderID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
m := &domain.Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.messages.Create(ctx, m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Если invalidate=false — кэш НЕ сбрасывается, будет stale read.
|
||||
if s.invalidate && s.cache != nil {
|
||||
_ = s.cache.Invalidate(ctx, chatID)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *MessageService) List(ctx context.Context, callerID, chatID, cursor string, limit int) ([]*domain.Message, string, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
|
||||
ok, err := s.chats.IsMember(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
return nil, "", err
|
||||
}
|
||||
if !ok {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
|
||||
// Попытка достать из кэша (только для первой страницы).
|
||||
if s.cache != nil && cursor == "" {
|
||||
if cached, hit := s.cache.Get(ctx, chatID, cursor); hit {
|
||||
return cached, "", nil
|
||||
}
|
||||
}
|
||||
|
||||
cursorTime := time.Unix(0, 0).UTC()
|
||||
cursorID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != "" {
|
||||
t, id, err := decodeCursor(cursor, chatID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
cursorTime, cursorID = t, id
|
||||
}
|
||||
|
||||
items, err := s.messages.ListByChat(ctx, chatID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if items == nil {
|
||||
items = []*domain.Message{}
|
||||
}
|
||||
|
||||
var next string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = encodeCursor(chatID, last.CreatedAt, last.ID)
|
||||
}
|
||||
|
||||
// Кэшируем только первую страницу.
|
||||
if s.cache != nil && cursor == "" {
|
||||
s.cache.Set(ctx, chatID, cursor, items)
|
||||
}
|
||||
|
||||
return items, next, nil
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository/memory"
|
||||
)
|
||||
|
||||
type messageFixture struct {
|
||||
users *UserService
|
||||
chats *ChatService
|
||||
messages *MessageService
|
||||
|
||||
aliceID string
|
||||
bobID string
|
||||
carolID string
|
||||
chatID string
|
||||
}
|
||||
|
||||
func newMessageFixture(t *testing.T) *messageFixture {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
|
||||
userRepo := memory.NewUserRepository()
|
||||
chatRepo := memory.NewChatRepository()
|
||||
msgRepo := memory.NewMessageRepository()
|
||||
|
||||
userSvc := NewUserService(userRepo)
|
||||
chatSvc := NewChatService(chatRepo, userRepo)
|
||||
msgSvc := NewMessageService(msgRepo, chatRepo)
|
||||
|
||||
alice, err := userSvc.Register(ctx, "alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("register alice: %v", err)
|
||||
}
|
||||
bob, err := userSvc.Register(ctx, "bob", "Боб")
|
||||
if err != nil {
|
||||
t.Fatalf("register bob: %v", err)
|
||||
}
|
||||
carol, err := userSvc.Register(ctx, "carol", "Кэрол")
|
||||
if err != nil {
|
||||
t.Fatalf("register carol: %v", err)
|
||||
}
|
||||
|
||||
chat, err := chatSvc.Create(ctx, alice.ID, "Project", []string{alice.ID, bob.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("create chat: %v", err)
|
||||
}
|
||||
|
||||
return &messageFixture{
|
||||
users: userSvc,
|
||||
chats: chatSvc,
|
||||
messages: msgSvc,
|
||||
aliceID: alice.ID,
|
||||
bobID: bob.ID,
|
||||
carolID: carol.ID,
|
||||
chatID: chat.ID,
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Send_OK(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
m, err := f.messages.Send(ctx, f.aliceID, f.chatID, "Привет, Боб!")
|
||||
if err != nil {
|
||||
t.Fatalf("Send failed: %v", err)
|
||||
}
|
||||
if m.Text != "Привет, Боб!" {
|
||||
t.Errorf("text mismatch: got %q", m.Text)
|
||||
}
|
||||
if m.SenderID != f.aliceID {
|
||||
t.Errorf("sender mismatch: got %q", m.SenderID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Send_Stranger(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := f.messages.Send(ctx, f.carolID, f.chatID, "Hello")
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound for stranger, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Send_NonexistentChat(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := f.messages.Send(ctx, f.aliceID, "nonexistent-chat", "Hello")
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Send_EmptyText(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
cases := []string{"", " ", "\t\n"}
|
||||
for _, text := range cases {
|
||||
_, err := f.messages.Send(ctx, f.aliceID, f.chatID, text)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("text %q: expected ErrInvalidInput, got %v", text, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Send_TooLongText(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
text := strings.Repeat("я", 4001)
|
||||
_, err := f.messages.Send(ctx, f.aliceID, f.chatID, text)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput for 4001 code points, got %v", err)
|
||||
}
|
||||
|
||||
text = strings.Repeat("я", 4000)
|
||||
if _, err := f.messages.Send(ctx, f.aliceID, f.chatID, text); err != nil {
|
||||
t.Fatalf("expected OK for 4000 code points, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_List_OK(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = f.messages.Send(ctx, f.aliceID, f.chatID, "one")
|
||||
_, _ = f.messages.Send(ctx, f.bobID, f.chatID, "two")
|
||||
|
||||
items, next, err := f.messages.List(ctx, f.aliceID, f.chatID, "", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("List failed: %v", err)
|
||||
}
|
||||
if len(items) != 2 {
|
||||
t.Fatalf("expected 2 messages, got %d", len(items))
|
||||
}
|
||||
if next != "" {
|
||||
t.Errorf("expected empty cursor, got %q", next)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_List_Stranger(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _, err := f.messages.List(ctx, f.carolID, f.chatID, "", 10)
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound for stranger, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_List_InvalidLimit(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
for _, limit := range []int{0, -1, 101} {
|
||||
_, _, err := f.messages.List(ctx, f.aliceID, f.chatID, "", limit)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("limit %d: expected ErrInvalidInput, got %v", limit, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_List_CursorFromAnotherChat(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
chat2, err := f.chats.Create(ctx, f.aliceID, "Other", []string{f.aliceID, f.carolID})
|
||||
if err != nil {
|
||||
t.Fatalf("create second chat: %v", err)
|
||||
}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
_, _ = f.messages.Send(ctx, f.aliceID, f.chatID, "in chat1")
|
||||
_, _ = f.messages.Send(ctx, f.aliceID, chat2.ID, "in chat2")
|
||||
}
|
||||
|
||||
// Получаем курсор из первого чата.
|
||||
_, cursor, err := f.messages.List(ctx, f.aliceID, f.chatID, "", 2)
|
||||
if err != nil {
|
||||
t.Fatalf("List chat1 failed: %v", err)
|
||||
}
|
||||
if cursor == "" {
|
||||
t.Fatal("expected non-empty cursor")
|
||||
}
|
||||
|
||||
// Пытаемся использовать его во втором чате.
|
||||
_, _, err = f.messages.List(ctx, f.aliceID, chat2.ID, cursor, 2)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput for cursor from another chat, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Pagination_AllMessages(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
const total = 10
|
||||
for i := 0; i < total; i++ {
|
||||
if _, err := f.messages.Send(ctx, f.aliceID, f.chatID, "msg"); err != nil {
|
||||
t.Fatalf("send %d failed: %v", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
seen := make(map[string]bool)
|
||||
cursor := ""
|
||||
pages := 0
|
||||
for {
|
||||
items, next, err := f.messages.List(ctx, f.aliceID, f.chatID, cursor, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("List failed: %v", err)
|
||||
}
|
||||
for _, m := range items {
|
||||
if seen[m.ID] {
|
||||
t.Errorf("duplicate message: %q", m.ID)
|
||||
}
|
||||
seen[m.ID] = true
|
||||
}
|
||||
pages++
|
||||
if next == "" {
|
||||
break
|
||||
}
|
||||
cursor = next
|
||||
if pages > 10 {
|
||||
t.Fatal("too many pages")
|
||||
}
|
||||
}
|
||||
if len(seen) != total {
|
||||
t.Errorf("expected %d unique messages, got %d", total, len(seen))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// Параметры Argon2id. Значения — стандартные рекомендации OWASP для интерактивного логина.
|
||||
const (
|
||||
argonTime = 1
|
||||
argonMemory = 64 * 1024 // 64 MiB
|
||||
argonThreads = 4
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
// ErrPasswordMismatch возвращается, если пароль не совпадает с хешем.
|
||||
// Не путать с "неверный формат хеша" — это тоже ошибка, но другая.
|
||||
var ErrPasswordMismatch = errors.New("password mismatch")
|
||||
|
||||
// hashPassword хеширует пароль через Argon2id и возвращает строку в формате
|
||||
// $argon2id$v=19$m=65536,t=1,p=4$<salt>$<hash>.
|
||||
func hashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate salt: %w", err)
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonTime, argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash),
|
||||
), nil
|
||||
}
|
||||
|
||||
// verifyPassword сравнивает пароль с хешем, возвращённым hashPassword.
|
||||
// Возвращает ErrPasswordMismatch, если пароль не подходит.
|
||||
func verifyPassword(password, encoded string) error {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return fmt.Errorf("invalid hash format")
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return fmt.Errorf("parse version: %w", err)
|
||||
}
|
||||
if version != argon2.Version {
|
||||
return fmt.Errorf("incompatible version: %d", version)
|
||||
}
|
||||
|
||||
var mem uint32
|
||||
var iters uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &mem, &iters, &threads); err != nil {
|
||||
return fmt.Errorf("parse params: %w", err)
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode salt: %w", err)
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode hash: %w", err)
|
||||
}
|
||||
|
||||
got := argon2.IDKey([]byte(password), salt, iters, mem, threads, uint32(len(want)))
|
||||
if subtle.ConstantTimeCompare(got, want) != 1 {
|
||||
return ErrPasswordMismatch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
users repository.UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(users repository.UserRepository) *UserService {
|
||||
return &UserService{users: users}
|
||||
}
|
||||
|
||||
// Register создаёт нового пользователя. Возвращает ErrInvalidInput при невалидных
|
||||
// данных и ErrConflict, если username занят.
|
||||
func (s *UserService) Register(ctx context.Context, username, displayName, password string) (*domain.User, error) {
|
||||
if !validateUsername(username) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if !validateDisplayName(displayName) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if !validatePassword(password) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
hash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
|
||||
u := &domain.User{
|
||||
ID: newID(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.users.Create(ctx, u, hash); err != nil {
|
||||
if errors.Is(err, repository.ErrConflict) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// GetByID возвращает пользователя. Возвращает ErrNotFound, если такого нет.
|
||||
// Используется middleware аутентификации для проверки X-User-Id.
|
||||
func (s *UserService) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
u, err := s.users.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository/memory"
|
||||
)
|
||||
|
||||
func newUserService() *UserService {
|
||||
return NewUserService(memory.NewUserRepository())
|
||||
}
|
||||
|
||||
func TestUserService_Register_OK(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
u, err := svc.Register(ctx, "alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("Register failed: %v", err)
|
||||
}
|
||||
if u.ID == "" {
|
||||
t.Error("expected non-empty ID")
|
||||
}
|
||||
if u.Username != "alice" {
|
||||
t.Errorf("username mismatch: got %q", u.Username)
|
||||
}
|
||||
if u.CreatedAt.IsZero() {
|
||||
t.Error("expected non-zero CreatedAt")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_Register_InvalidUsername(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
username string
|
||||
}{
|
||||
{"too short", "ab"},
|
||||
{"too long", strings.Repeat("a", 33)},
|
||||
{"uppercase", "Alice"},
|
||||
{"with dash", "al-ice"},
|
||||
{"with space", "al ice"},
|
||||
{"empty", ""},
|
||||
{"only spaces", " "},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := svc.Register(ctx, tc.username, "Test")
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_Register_InvalidDisplayName(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
displayName string
|
||||
}{
|
||||
{"empty", ""},
|
||||
{"only spaces", " "},
|
||||
{"too long", strings.Repeat("я", 101)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := svc.Register(ctx, "alice", tc.displayName)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_Register_UnicodeDisplayName_OK(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
// 100 code points ровно — должно пройти.
|
||||
name := strings.Repeat("я", 100)
|
||||
if _, err := svc.Register(ctx, "alice", name); err != nil {
|
||||
t.Fatalf("expected OK for 100 code points, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_Register_DuplicateUsername(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := svc.Register(ctx, "alice", "Алиса"); err != nil {
|
||||
t.Fatalf("first Register failed: %v", err)
|
||||
}
|
||||
_, err := svc.Register(ctx, "alice", "Another")
|
||||
if !errors.Is(err, ErrConflict) {
|
||||
t.Fatalf("expected ErrConflict, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_GetByID_NotFound(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := svc.GetByID(ctx, "nonexistent")
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func validatePassword(s string) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 12 && n <= 128
|
||||
}
|
||||
|
||||
// validateUsername проверяет формат username по README: строго [a-z0-9_]{3,32}.
|
||||
func validateUsername(s string) bool {
|
||||
return usernameRe.MatchString(s)
|
||||
}
|
||||
|
||||
// validateDisplayName проверяет display_name: 1–100 Unicode code points,
|
||||
// не состоит только из пробельных символов.
|
||||
func validateDisplayName(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 100
|
||||
}
|
||||
|
||||
// validateTitle проверяет title чата: 1–100 code points, не только пробелы.
|
||||
func validateTitle(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 100
|
||||
}
|
||||
|
||||
// validateText проверяет text сообщения: 1–4000 code points, не только пробелы.
|
||||
// В lab4 появится возможность отправить пустой text, если есть attachment_ids.
|
||||
func validateText(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 4000
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/service"
|
||||
"github.com/charawein/mtusi2026lab2/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
auth *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(auth *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{auth: auth}
|
||||
}
|
||||
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User *domain.User `json:"user"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
username, password, ok := parseBasicAuth(r.Header.Get("Authorization"))
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
sess, u, err := h.auth.Login(r.Context(), username, password)
|
||||
if err != nil {
|
||||
if err == service.ErrUnauthorized {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Формат RFC3339 без микросекунд: "2026-10-09T19:00:36Z".
|
||||
// Python-клиент тестов ожидает 'Z' в конце строки.
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, sessionResponse{
|
||||
Token: sess.Token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: sess.ExpiresAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
User: u,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
token := bearerToken(r)
|
||||
if token == "" {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
if err := h.auth.Logout(r.Context(), token); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func parseBasicAuth(h string) (string, string, bool) {
|
||||
const prefix = "Basic "
|
||||
if !strings.HasPrefix(h, prefix) {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(h[len(prefix):])
|
||||
if err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
parts := strings.SplitN(string(raw), ":", 2)
|
||||
if len(parts) != 2 {
|
||||
return "", "", false
|
||||
}
|
||||
return parts[0], parts[1], true
|
||||
}
|
||||
|
||||
func bearerToken(r *http.Request) string {
|
||||
h := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(h, "Bearer ") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimPrefix(h, "Bearer ")
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/service"
|
||||
"github.com/charawein/mtusi2026lab2/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chats *service.ChatService
|
||||
}
|
||||
|
||||
func NewChatHandler(chats *service.ChatService) *ChatHandler {
|
||||
return &ChatHandler{chats: chats}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := httputil.DecodeJSON(r, &body); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
c, err := h.chats.Create(r.Context(), uid, body.Title, body.MemberIDs)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, c)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
limit, err := httputil.ParseLimit(r)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
|
||||
items, next, err := h.chats.List(r.Context(), uid, cursor, limit)
|
||||
if err != nil {
|
||||
// ВРЕМЕННО: логируем точную ошибку
|
||||
slog.Error("ListChats failed", "err", err, "uid", uid, "cursor", cursor, "limit", limit)
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, httputil.PageResponse{Items: items, NextCursor: httputil.NextOrNull(next)})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if chatID == "" {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
c, err := h.chats.Get(r.Context(), uid, chatID)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, c)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type HealthHandler struct{}
|
||||
|
||||
func NewHealthHandler() *HealthHandler {
|
||||
return &HealthHandler{}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
|
||||
httputil.WriteJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
httputil.WriteJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/service"
|
||||
"github.com/charawein/mtusi2026lab2/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type MessageHandler struct {
|
||||
messages *service.MessageService
|
||||
}
|
||||
|
||||
func NewMessageHandler(messages *service.MessageService) *MessageHandler {
|
||||
return &MessageHandler{messages: messages}
|
||||
}
|
||||
|
||||
func (h *MessageHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if chatID == "" {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := httputil.DecodeJSON(r, &body); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
m, err := h.messages.Send(r.Context(), uid, chatID, body.Text)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, m)
|
||||
}
|
||||
|
||||
func (h *MessageHandler) ListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if chatID == "" {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
limit, err := httputil.ParseLimit(r)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
|
||||
items, next, err := h.messages.List(r.Context(), uid, chatID, cursor, limit)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, httputil.PageResponse{Items: items, NextCursor: httputil.NextOrNull(next)})
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/service"
|
||||
"github.com/charawein/mtusi2026lab2/internal/transport/httputil"
|
||||
)
|
||||
|
||||
// Auth проверяет Authorization: Bearer <token> через AuthService.
|
||||
func Auth(auth *service.AuthService) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
header := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
token := strings.TrimPrefix(header, "Bearer ")
|
||||
if token == "" {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
u, err := auth.ValidateSession(r.Context(), token)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
slog.Error("auth: unexpected", "err", err)
|
||||
httputil.WriteError(w, r, nil)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := httputil.ContextWithUserID(r.Context(), u.ID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func writeUnauthorized(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(code int) {
|
||||
r.status = code
|
||||
r.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rec, r)
|
||||
slog.Info("http request",
|
||||
"request_id", httputil.RequestIDFrom(r.Context()),
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", rec.status,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/transport/httputil"
|
||||
)
|
||||
|
||||
func Recovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
slog.Error("panic in handler",
|
||||
"panic", rec,
|
||||
"request_id", httputil.RequestIDFrom(r.Context()),
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
)
|
||||
httputil.WriteError(w, r, nil)
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/transport/httputil"
|
||||
)
|
||||
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get("X-Request-Id")
|
||||
if id == "" {
|
||||
id = newRequestID()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
ctx := httputil.ContextWithRequestID(r.Context(), id)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func newRequestID() string {
|
||||
var b [12]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
||||
}
|
||||
return fmt.Sprintf("%x", b[:])
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/service"
|
||||
"github.com/charawein/mtusi2026lab2/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
func NewRouter(
|
||||
users *service.UserService,
|
||||
chats *service.ChatService,
|
||||
messages *service.MessageService,
|
||||
auth *service.AuthService,
|
||||
) http.Handler {
|
||||
userH := NewUserHandler(users)
|
||||
chatH := NewChatHandler(chats)
|
||||
msgH := NewMessageHandler(messages)
|
||||
authH := NewAuthHandler(auth)
|
||||
healthH := NewHealthHandler()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("GET /health/live", healthH.Live)
|
||||
mux.HandleFunc("GET /health/ready", healthH.Ready)
|
||||
mux.HandleFunc("POST /api/v1/users", userH.CreateUser)
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", authH.CreateSession)
|
||||
|
||||
// Debug endpoints для демонстрации трека 5.1 (не входят в публичный контракт).
|
||||
mux.HandleFunc("POST /debug/cache/on", func(w http.ResponseWriter, r *http.Request) {
|
||||
messages.SetInvalidate(true)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
mux.HandleFunc("POST /debug/cache/off", func(w http.ResponseWriter, r *http.Request) {
|
||||
messages.SetInvalidate(false)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
|
||||
authMW := middleware.Auth(auth)
|
||||
|
||||
mux.Handle("DELETE /api/v1/auth/sessions/current", authMW(http.HandlerFunc(authH.RevokeSession)))
|
||||
mux.Handle("GET /api/v1/users/me", authMW(http.HandlerFunc(userH.CurrentUser)))
|
||||
mux.Handle("POST /api/v1/chats", authMW(http.HandlerFunc(chatH.CreateChat)))
|
||||
mux.Handle("GET /api/v1/chats", authMW(http.HandlerFunc(chatH.ListChats)))
|
||||
mux.Handle("GET /api/v1/chats/{chat_id}", authMW(http.HandlerFunc(chatH.GetChat)))
|
||||
mux.Handle("POST /api/v1/chats/{chat_id}/messages", authMW(http.HandlerFunc(msgH.SendMessage)))
|
||||
mux.Handle("GET /api/v1/chats/{chat_id}/messages", authMW(http.HandlerFunc(msgH.ListMessages)))
|
||||
|
||||
handler := middleware.Logging(mux)
|
||||
handler = middleware.Recovery(handler)
|
||||
handler = middleware.RequestID(handler)
|
||||
return handler
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/service"
|
||||
"github.com/charawein/mtusi2026lab2/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
users *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(users *service.UserService) *UserHandler {
|
||||
return &UserHandler{users: users}
|
||||
}
|
||||
|
||||
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := httputil.DecodeJSON(r, &body); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
u, err := h.users.Register(r.Context(), body.Username, body.DisplayName, body.Password)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, u)
|
||||
}
|
||||
|
||||
func (h *UserHandler) CurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
u, err := h.users.GetByID(r.Context(), uid)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, u)
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package httputil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/service"
|
||||
)
|
||||
|
||||
// requestIDKey — ключ контекста для X-Request-Id.
|
||||
type requestIDKey struct{}
|
||||
|
||||
// ContextWithRequestID кладёт request_id в контекст. Используется middleware.RequestID.
|
||||
func ContextWithRequestID(ctx context.Context, id string) context.Context {
|
||||
return context.WithValue(ctx, requestIDKey{}, id)
|
||||
}
|
||||
|
||||
// RequestIDFrom извлекает request_id из контекста.
|
||||
func RequestIDFrom(ctx context.Context) string {
|
||||
if v, ok := ctx.Value(requestIDKey{}).(string); ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// userIDKey — ключ контекста для аутентифицированного user_id.
|
||||
type userIDKey struct{}
|
||||
|
||||
// ContextWithUserID кладёт user_id в контекст. Используется middleware.Auth.
|
||||
func ContextWithUserID(ctx context.Context, id string) context.Context {
|
||||
return context.WithValue(ctx, userIDKey{}, id)
|
||||
}
|
||||
|
||||
// UserIDFromContext извлекает user_id из контекста.
|
||||
func UserIDFromContext(ctx context.Context) string {
|
||||
if v, ok := ctx.Value(userIDKey{}).(string); ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// errorBody — формат тела ошибки по contracts/openapi.json.
|
||||
type errorBody struct {
|
||||
Error errorDetail `json:"error"`
|
||||
}
|
||||
|
||||
type errorDetail struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// WriteJSON пишет JSON-ответ с заданным статусом.
|
||||
func WriteJSON(w http.ResponseWriter, r *http.Request, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
slog.Error("failed to encode response", "err", err, "request_id", RequestIDFrom(r.Context()))
|
||||
}
|
||||
}
|
||||
|
||||
// WriteError мапит доменную ошибку в HTTP-статус и пишет тело в формате контракта.
|
||||
func WriteError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
status, code := mapError(err)
|
||||
reqID := RequestIDFrom(r.Context())
|
||||
if reqID == "" {
|
||||
reqID = "missing-request-id"
|
||||
}
|
||||
body := errorBody{Error: errorDetail{
|
||||
Code: code,
|
||||
Message: messageFor(code),
|
||||
RequestID: reqID,
|
||||
}}
|
||||
WriteJSON(w, r, status, body)
|
||||
}
|
||||
|
||||
func mapError(err error) (int, string) {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrInvalidInput):
|
||||
return http.StatusBadRequest, "invalid_request"
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
return http.StatusUnauthorized, "unauthorized"
|
||||
case errors.Is(err, service.ErrNotFound):
|
||||
return http.StatusNotFound, "not_found"
|
||||
case errors.Is(err, service.ErrConflict):
|
||||
return http.StatusConflict, "conflict"
|
||||
default:
|
||||
return http.StatusInternalServerError, "internal_error"
|
||||
}
|
||||
}
|
||||
|
||||
func messageFor(code string) string {
|
||||
switch code {
|
||||
case "invalid_request":
|
||||
return "Неверный запрос"
|
||||
case "unauthorized":
|
||||
return "Требуется аутентификация"
|
||||
case "not_found":
|
||||
return "Объект не найден"
|
||||
case "conflict":
|
||||
return "Конфликт"
|
||||
case "internal_error":
|
||||
return "Внутренняя ошибка"
|
||||
default:
|
||||
return "Ошибка"
|
||||
}
|
||||
}
|
||||
|
||||
// DecodeJSON парсит тело запроса в v, строго запрещая неизвестные поля.
|
||||
func DecodeJSON(r *http.Request, v any) error {
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(v); err != nil {
|
||||
return service.ErrInvalidInput
|
||||
}
|
||||
if dec.More() {
|
||||
return service.ErrInvalidInput
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseLimit читает query-параметр limit с дефолтом и границами по контракту.
|
||||
func ParseLimit(r *http.Request) (int, error) {
|
||||
s := r.URL.Query().Get("limit")
|
||||
if s == "" {
|
||||
return 50, nil
|
||||
}
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, service.ErrInvalidInput
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// PageResponse — универсальный ответ пагинации.
|
||||
type PageResponse struct {
|
||||
Items any `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// NextOrNull превращает пустую строку в nil (для сериализации в null).
|
||||
func NextOrNull(s string) *string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return &s
|
||||
}
|
||||
Reference in New Issue
Block a user