Implement lab 3 level 4 failover and idempotency
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Database struct {
|
||||
PostgresURL string
|
||||
RedisAddr string
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
HTTP struct {
|
||||
Host string
|
||||
Port string
|
||||
}
|
||||
Database Database
|
||||
|
||||
Session struct {
|
||||
TTL time.Duration
|
||||
Store string
|
||||
}
|
||||
|
||||
AppEnv string
|
||||
CacheURL string
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
config := &Config{}
|
||||
sessionTTL, err := getSessionTTL()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.Session.TTL = sessionTTL
|
||||
|
||||
config.HTTP.Host = os.Getenv("APP_HOST")
|
||||
if config.HTTP.Host == "" {
|
||||
config.HTTP.Host = "0.0.0.0"
|
||||
}
|
||||
|
||||
config.HTTP.Port = os.Getenv("APP_PORT")
|
||||
if config.HTTP.Port == "" {
|
||||
config.HTTP.Port = "8080"
|
||||
}
|
||||
|
||||
config.AppEnv = os.Getenv("APP_ENV")
|
||||
if config.AppEnv == "" {
|
||||
config.AppEnv = "lab"
|
||||
}
|
||||
|
||||
store := os.Getenv("SESSION_STORE")
|
||||
|
||||
config.Session.Store = strings.TrimSpace(string(store))
|
||||
if config.Session.Store == "" {
|
||||
return nil, fmt.Errorf("empty session store data")
|
||||
}
|
||||
|
||||
config.Database, err = getDatabaseURL()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
|
||||
}
|
||||
|
||||
func getSessionTTL() (time.Duration, error) {
|
||||
value, ok := os.LookupEnv("SESSION_TTL_SECONDS")
|
||||
if !ok {
|
||||
return time.Hour, nil
|
||||
}
|
||||
|
||||
seconds, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || seconds <= 0 || seconds > int64((1<<63-1)/int64(time.Second)) {
|
||||
return 0, fmt.Errorf("invalid SESSION_TTL_SECONDS: %q", value)
|
||||
}
|
||||
|
||||
return time.Duration(seconds) * time.Second, nil
|
||||
}
|
||||
|
||||
func getDatabaseURL() (Database, error) {
|
||||
db := Database{}
|
||||
|
||||
postgressPath := os.Getenv("DATABASE_URL_FILE")
|
||||
|
||||
postgresData, err := os.ReadFile(postgressPath)
|
||||
if err != nil {
|
||||
return db, fmt.Errorf("read database URL: %w", err)
|
||||
}
|
||||
|
||||
db.PostgresURL = strings.TrimSpace(string(postgresData))
|
||||
|
||||
redisData := os.Getenv("REDIS_ADDR")
|
||||
|
||||
db.RedisAddr = strings.TrimSpace(string(redisData))
|
||||
|
||||
if db.RedisAddr == "" {
|
||||
return db, fmt.Errorf("redis addres is empty")
|
||||
}
|
||||
|
||||
return db, nil
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func NewPostgres(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func NewRedis(ctx context.Context, addr string) (*redis.Client, error) {
|
||||
|
||||
options := &redis.Options{
|
||||
Addr: addr,
|
||||
DialTimeout: 3 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 2 * time.Second,
|
||||
PoolSize: 10,
|
||||
PoolTimeout: 2 * time.Second,
|
||||
ContextTimeoutEnabled: true,
|
||||
}
|
||||
|
||||
client := redis.NewClient(options)
|
||||
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return client, nil
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: chat_members.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const createChatMember = `-- name: CreateChatMember :exec
|
||||
INSERT INTO chat_members(chat_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
`
|
||||
|
||||
type CreateChatMemberParams struct {
|
||||
ChatID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) CreateChatMember(ctx context.Context, arg CreateChatMemberParams) error {
|
||||
_, err := q.db.Exec(ctx, createChatMember, arg.ChatID, arg.UserID)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: chats.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const createChat = `-- name: CreateChat :one
|
||||
INSERT INTO chats (title)
|
||||
VALUES ($1)
|
||||
RETURNING id, title, created_at
|
||||
`
|
||||
|
||||
func (q *Queries) CreateChat(ctx context.Context, title string) (Chat, error) {
|
||||
row := q.db.QueryRow(ctx, createChat, title)
|
||||
var i Chat
|
||||
err := row.Scan(&i.ID, &i.Title, &i.CreatedAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getChatByID = `-- name: GetChatByID :one
|
||||
|
||||
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1
|
||||
GROUP BY c.id
|
||||
`
|
||||
|
||||
type GetChatByIDRow struct {
|
||||
ID pgtype.UUID
|
||||
Title string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
MemberIds []pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetChatByID(ctx context.Context, id pgtype.UUID) (GetChatByIDRow, error) {
|
||||
row := q.db.QueryRow(ctx, getChatByID, id)
|
||||
var i GetChatByIDRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.MemberIds,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getChatsByUserID = `-- name: GetChatsByUserID :many
|
||||
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE EXISTS (SELECT 1
|
||||
FROM chat_members membership
|
||||
WHERE membership.chat_id = c.id
|
||||
AND membership.user_id = $1)
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (c.created_at, c.id) >
|
||||
(
|
||||
$2::timestamptz,
|
||||
$3::uuid
|
||||
)
|
||||
)
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type GetChatsByUserIDParams struct {
|
||||
UserID pgtype.UUID
|
||||
AfterCreatedAt pgtype.Timestamptz
|
||||
AfterID pgtype.UUID
|
||||
LimitCount int32
|
||||
}
|
||||
|
||||
type GetChatsByUserIDRow struct {
|
||||
ID pgtype.UUID
|
||||
Title string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
MemberIds []pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetChatsByUserID(ctx context.Context, arg GetChatsByUserIDParams) ([]GetChatsByUserIDRow, error) {
|
||||
rows, err := q.db.Query(ctx, getChatsByUserID,
|
||||
arg.UserID,
|
||||
arg.AfterCreatedAt,
|
||||
arg.AfterID,
|
||||
arg.LimitCount,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []GetChatsByUserIDRow
|
||||
for rows.Next() {
|
||||
var i GetChatsByUserIDRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.MemberIds,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type DBTX interface {
|
||||
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(context.Context, string, ...interface{}) pgx.Row
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
return &Queries{db: db}
|
||||
}
|
||||
|
||||
type Queries struct {
|
||||
db DBTX
|
||||
}
|
||||
|
||||
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
|
||||
return &Queries{
|
||||
db: tx,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: message_idempotentency.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getIdempotentMessage = `-- name: GetIdempotentMessage :one
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM message_idempotency AS i
|
||||
JOIN messages AS m ON m.id = i.message_id
|
||||
WHERE i.user_id = $1
|
||||
AND i.chat_id = $2
|
||||
AND i.idempotency_key = $3
|
||||
`
|
||||
|
||||
type GetIdempotentMessageParams struct {
|
||||
UserID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
func (q *Queries) GetIdempotentMessage(ctx context.Context, arg GetIdempotentMessageParams) (Message, error) {
|
||||
row := q.db.QueryRow(ctx, getIdempotentMessage, arg.UserID, arg.ChatID, arg.IdempotencyKey)
|
||||
var i Message
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertMessageIdempotency = `-- name: InsertMessageIdempotency :execrows
|
||||
INSERT INTO message_idempotency(user_id, chat_id, idempotency_key, message_id)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (user_id, chat_id, idempotency_key) DO NOTHING
|
||||
`
|
||||
|
||||
type InsertMessageIdempotencyParams struct {
|
||||
UserID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
IdempotencyKey string
|
||||
MessageID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) InsertMessageIdempotency(ctx context.Context, arg InsertMessageIdempotencyParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, insertMessageIdempotency,
|
||||
arg.UserID,
|
||||
arg.ChatID,
|
||||
arg.IdempotencyKey,
|
||||
arg.MessageID,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: messages.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const createMessage = `-- name: CreateMessage :one
|
||||
INSERT INTO messages (chat_id, sender_id, text)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
`
|
||||
|
||||
type CreateMessageParams struct {
|
||||
ChatID pgtype.UUID
|
||||
SenderID pgtype.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {
|
||||
row := q.db.QueryRow(ctx, createMessage, arg.ChatID, arg.SenderID, arg.Text)
|
||||
var i Message
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getMessagesByChatID = `-- name: GetMessagesByChatID :many
|
||||
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (created_at, id) >
|
||||
($2::timestamptz,
|
||||
$3::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type GetMessagesByChatIDParams struct {
|
||||
ChatID pgtype.UUID
|
||||
AfterCreatedAt pgtype.Timestamptz
|
||||
AfterID pgtype.UUID
|
||||
LimitCount int32
|
||||
}
|
||||
|
||||
func (q *Queries) GetMessagesByChatID(ctx context.Context, arg GetMessagesByChatIDParams) ([]Message, error) {
|
||||
rows, err := q.db.Query(ctx, getMessagesByChatID,
|
||||
arg.ChatID,
|
||||
arg.AfterCreatedAt,
|
||||
arg.AfterID,
|
||||
arg.LimitCount,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Message
|
||||
for rows.Next() {
|
||||
var i Message
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID pgtype.UUID
|
||||
Title string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type ChatMember struct {
|
||||
ChatID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
SenderID pgtype.UUID
|
||||
Text string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type MessageIdempotency struct {
|
||||
UserID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
IdempotencyKey string
|
||||
MessageID pgtype.UUID
|
||||
CreatedAt pgtype.Timestamptz
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID pgtype.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: users.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const createUser = `-- name: CreateUser :one
|
||||
|
||||
INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, username, display_name, password_hash, created_at
|
||||
`
|
||||
|
||||
type CreateUserParams struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) {
|
||||
row := q.db.QueryRow(ctx, createUser, arg.Username, arg.DisplayName, arg.PasswordHash)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.PasswordHash,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByID = `-- name: GetUserByID :one
|
||||
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByID, id)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.PasswordHash,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByUsername = `-- name: GetUserByUsername :one
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByUsername, username)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.PasswordHash,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Chat struct {
|
||||
ID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Message struct {
|
||||
ID string
|
||||
ChatID string
|
||||
SenderID string
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Session struct {
|
||||
TokenHash []byte
|
||||
UserID string
|
||||
CreatedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
RevokedAt *time.Time
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID string
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ChatRepository interface {
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string) (*model.Chat, error)
|
||||
GetChatByID(ctx context.Context, id string) (*model.Chat, error)
|
||||
GetChatsByUserID(ctx context.Context, userID string, limit int, after *ChatPosition) ([]*model.Chat, error)
|
||||
}
|
||||
|
||||
type ChatPosition struct {
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrAlreadyExists = errors.New("already exists")
|
||||
ErrDatabase = errors.New("database error")
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrServiceUnavailable = errors.New("database unavailable")
|
||||
ErrServerError = errors.New("server error")
|
||||
ErrRedisNotAnswer = errors.New("redis not not answer")
|
||||
ErrConflict = errors.New("data conflict")
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type MessageRepository interface {
|
||||
CreateMessage(ctx context.Context, chatID, senderID, text, key string) (*model.Message, error)
|
||||
GetMessagesByChatID(ctx context.Context, chatID string, limit int, after *MessagePosition) ([]*model.Message, error)
|
||||
}
|
||||
|
||||
type MessagePosition struct {
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type ChatRepository struct {
|
||||
queries *sqlc.Queries
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatRepository(queries *sqlc.Queries, pool *pgxpool.Pool) *ChatRepository {
|
||||
return &ChatRepository{
|
||||
queries: queries,
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ChatRepository) CreateChat(ctx context.Context, title string, memberIDs []string) (*model.Chat, error) {
|
||||
txCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
rollbackCtx, rollbackCancel := context.WithTimeout(
|
||||
context.WithoutCancel(ctx),
|
||||
time.Second,
|
||||
)
|
||||
defer rollbackCancel()
|
||||
|
||||
_ = tx.Rollback(rollbackCtx)
|
||||
}()
|
||||
txQueries := r.queries.WithTx(tx)
|
||||
|
||||
sqlcChat, err := txQueries.CreateChat(txCtx, title)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
chat := &model.Chat{
|
||||
ID: sqlcChat.ID.String(),
|
||||
Title: sqlcChat.Title,
|
||||
CreatedAt: sqlcChat.CreatedAt.Time,
|
||||
}
|
||||
|
||||
for _, id := range memberIDs {
|
||||
userID, err := getUUIDFromString(id)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
err = txQueries.CreateChatMember(txCtx, sqlc.CreateChatMemberParams{ChatID: sqlcChat.ID, UserID: *userID})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
chat.MemberIDs = slices.Clone(memberIDs)
|
||||
|
||||
err = tx.Commit(txCtx)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetChatByID(ctx context.Context, id string) (*model.Chat, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidID, err := getUUIDFromString(id)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
sqlcChat, err := r.queries.GetChatByID(dbCtx, *uuidID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
chat := mapChatSqlcToModel(&sqlcChat)
|
||||
|
||||
return chat, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetChatsByUserID(ctx context.Context, userID string, limit int, after *repository.ChatPosition) ([]*model.Chat, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidUserID, err := getUUIDFromString(userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
afterCreatedAt := pgtype.Timestamptz{Valid: false}
|
||||
afterID := pgtype.UUID{Valid: false}
|
||||
|
||||
if after != nil {
|
||||
afterCreatedAt = pgtype.Timestamptz{Time: after.CreatedAt, Valid: true}
|
||||
if uuidFromString, err := getUUIDFromString(after.ID); err == nil {
|
||||
afterID = *uuidFromString
|
||||
} else {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
chats, err := r.queries.GetChatsByUserID(dbCtx, sqlc.GetChatsByUserIDParams{UserID: *uuidUserID, AfterCreatedAt: afterCreatedAt, AfterID: afterID, LimitCount: int32(limit)})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
resultChats := make([]*model.Chat, len(chats))
|
||||
for index, sqlcChat := range chats {
|
||||
memberIDs := make([]string, len(sqlcChat.MemberIds))
|
||||
|
||||
for i, memberID := range sqlcChat.MemberIds {
|
||||
memberIDs[i] = memberID.String()
|
||||
}
|
||||
|
||||
resultChats[index] = &model.Chat{
|
||||
ID: sqlcChat.ID.String(),
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: sqlcChat.CreatedAt.Time,
|
||||
Title: sqlcChat.Title,
|
||||
}
|
||||
}
|
||||
|
||||
return resultChats, nil
|
||||
}
|
||||
|
||||
func mapChatSqlcToModel(sqlcChat *sqlc.GetChatByIDRow) *model.Chat {
|
||||
|
||||
memberIDs := make([]string, len(sqlcChat.MemberIds))
|
||||
|
||||
for i, memberID := range sqlcChat.MemberIds {
|
||||
memberIDs[i] = memberID.String()
|
||||
}
|
||||
|
||||
return &model.Chat{
|
||||
ID: sqlcChat.ID.String(),
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: sqlcChat.CreatedAt.Time,
|
||||
Title: sqlcChat.Title,
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"highload/internal/repository"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func convertDBError(err error) error {
|
||||
var pgErr *pgconn.PgError
|
||||
var netErr *net.OpError
|
||||
var dnsErr *net.DNSError
|
||||
|
||||
switch {
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return fmt.Errorf("%w: %v", repository.ErrServiceUnavailable, err)
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return repository.ErrNotFound
|
||||
case errors.As(err, &pgErr):
|
||||
switch pgErr.Code {
|
||||
case "23505":
|
||||
return repository.ErrAlreadyExists
|
||||
case "53300", "57P03", "08006", "08001", "57P01", "57P02":
|
||||
return repository.ErrServiceUnavailable
|
||||
}
|
||||
case errors.Is(err, io.EOF) ||
|
||||
errors.Is(err, io.ErrUnexpectedEOF) ||
|
||||
errors.Is(err, pgconn.ErrConnClosed):
|
||||
return repository.ErrServiceUnavailable
|
||||
case errors.Is(err, repository.ErrInvalidInput):
|
||||
return repository.ErrInvalidInput
|
||||
case errors.As(err, &netErr):
|
||||
return repository.ErrServiceUnavailable
|
||||
case errors.As(err, &dnsErr):
|
||||
return repository.ErrServiceUnavailable
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %v", repository.ErrDatabase, err)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
queries *sqlc.Queries
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageRepository(queries *sqlc.Queries, pool *pgxpool.Pool) *MessageRepository {
|
||||
return &MessageRepository{
|
||||
queries: queries,
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *MessageRepository) CreateMessage(ctx context.Context, chatID, senderID, text, key string) (*model.Message, error) {
|
||||
|
||||
uuidChatID, err := getUUIDFromString(chatID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
txCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
uuidSenderID, err := getUUIDFromString(senderID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
rollbackCtx, rollbackCancel := context.WithTimeout(
|
||||
context.WithoutCancel(ctx),
|
||||
time.Second,
|
||||
)
|
||||
defer rollbackCancel()
|
||||
|
||||
_ = tx.Rollback(rollbackCtx)
|
||||
}()
|
||||
|
||||
txQueries := r.queries.WithTx(tx)
|
||||
|
||||
sqlcMessage, err := txQueries.CreateMessage(txCtx, sqlc.CreateMessageParams{ChatID: *uuidChatID, SenderID: *uuidSenderID, Text: text})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
rowsAffected, err := txQueries.InsertMessageIdempotency(txCtx, sqlc.InsertMessageIdempotencyParams{UserID: sqlcMessage.SenderID, ChatID: sqlcMessage.ChatID, IdempotencyKey: key, MessageID: sqlcMessage.ID})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
switch rowsAffected {
|
||||
case 1:
|
||||
err := tx.Commit(txCtx)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
case 0:
|
||||
rollbackCtx, rollbackCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second)
|
||||
err := tx.Rollback(rollbackCtx)
|
||||
rollbackCancel()
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
sqlcMessage, err = r.queries.GetIdempotentMessage(dbCtx, sqlc.GetIdempotentMessageParams{UserID: sqlcMessage.SenderID, ChatID: sqlcMessage.ChatID, IdempotencyKey: key})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
if sqlcMessage.Text != text {
|
||||
return nil, repository.ErrConflict
|
||||
}
|
||||
|
||||
default:
|
||||
return nil, repository.ErrServerError
|
||||
}
|
||||
|
||||
message := &model.Message{
|
||||
ID: sqlcMessage.ID.String(),
|
||||
ChatID: sqlcMessage.ChatID.String(),
|
||||
SenderID: sqlcMessage.SenderID.String(),
|
||||
Text: sqlcMessage.Text,
|
||||
CreatedAt: sqlcMessage.CreatedAt.Time,
|
||||
}
|
||||
|
||||
return message, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *MessageRepository) GetMessagesByChatID(ctx context.Context, chatID string, limit int, after *repository.MessagePosition) ([]*model.Message, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidChatID, err := getUUIDFromString(chatID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
afterCreatedAt := pgtype.Timestamptz{Valid: false}
|
||||
afterID := pgtype.UUID{Valid: false}
|
||||
|
||||
if after != nil {
|
||||
afterCreatedAt = pgtype.Timestamptz{Time: after.CreatedAt, Valid: true}
|
||||
if uuidFromString, err := getUUIDFromString(after.ID); err == nil {
|
||||
afterID = *uuidFromString
|
||||
} else {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
sqlcMessages, err := r.queries.GetMessagesByChatID(dbCtx, sqlc.GetMessagesByChatIDParams{ChatID: *uuidChatID, AfterID: afterID, AfterCreatedAt: afterCreatedAt, LimitCount: int32(limit)})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
messages := make([]*model.Message, len(sqlcMessages))
|
||||
|
||||
for index, sqlcMessage := range sqlcMessages {
|
||||
messages[index] = &model.Message{
|
||||
ID: sqlcMessage.ID.String(),
|
||||
ChatID: sqlcMessage.ChatID.String(),
|
||||
SenderID: sqlcMessage.SenderID.String(),
|
||||
Text: sqlcMessage.Text,
|
||||
CreatedAt: sqlcMessage.CreatedAt.Time}
|
||||
}
|
||||
|
||||
return messages, nil
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func NewUserRepository(queries *sqlc.Queries) *UserRepository {
|
||||
return &UserRepository{queries: queries}
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, username, displayName string, passwordHash string) (*model.User, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
sqlcUser, err := r.queries.CreateUser(dbCtx, sqlc.CreateUserParams{Username: username, DisplayName: displayName, PasswordHash: passwordHash})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
user := &model.User{
|
||||
ID: sqlcUser.ID.String(),
|
||||
Username: sqlcUser.Username,
|
||||
DisplayName: sqlcUser.DisplayName,
|
||||
CreatedAt: sqlcUser.CreatedAt.Time,
|
||||
PasswordHash: sqlcUser.PasswordHash,
|
||||
}
|
||||
|
||||
return user, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetUserByID(ctx context.Context, id string) (*model.User, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidID, err := getUUIDFromString(id)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
sqlcUser, err := r.queries.GetUserByID(dbCtx, *uuidID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
user := &model.User{
|
||||
ID: sqlcUser.ID.String(),
|
||||
Username: sqlcUser.Username,
|
||||
DisplayName: sqlcUser.DisplayName,
|
||||
CreatedAt: sqlcUser.CreatedAt.Time,
|
||||
PasswordHash: sqlcUser.PasswordHash,
|
||||
}
|
||||
|
||||
return user, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetUserByUsername(ctx context.Context, username string) (*model.User, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
sqlcUser, err := r.queries.GetUserByUsername(dbCtx, username)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
user := &model.User{
|
||||
ID: sqlcUser.ID.String(),
|
||||
Username: sqlcUser.Username,
|
||||
DisplayName: sqlcUser.DisplayName,
|
||||
CreatedAt: sqlcUser.CreatedAt.Time,
|
||||
PasswordHash: sqlcUser.PasswordHash,
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"highload/internal/repository"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
func getUUIDFromString(id string) (*pgtype.UUID, error) {
|
||||
var uuidID pgtype.UUID
|
||||
|
||||
if err := uuidID.Scan(id); err != nil {
|
||||
return nil, repository.ErrInvalidInput
|
||||
}
|
||||
|
||||
return &uuidID, nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"highload/internal/repository"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func convertDBError(err error) error {
|
||||
|
||||
category := repository.ErrDatabase
|
||||
|
||||
var netErr *net.OpError
|
||||
|
||||
if errors.Is(err, redis.Nil) {
|
||||
category = repository.ErrNotFound
|
||||
}
|
||||
if errors.As(err, &netErr) {
|
||||
category = repository.ErrServiceUnavailable
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
category = repository.ErrServiceUnavailable
|
||||
}
|
||||
if errors.Is(err, redis.ErrPoolTimeout) {
|
||||
category = repository.ErrServiceUnavailable
|
||||
}
|
||||
if errors.Is(err, io.EOF) ||
|
||||
errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
category = repository.ErrServiceUnavailable
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %v", category, err)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json/v2"
|
||||
"fmt"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type SessionRepository struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionRepository(client *redis.Client) *SessionRepository {
|
||||
return &SessionRepository{client: client}
|
||||
}
|
||||
|
||||
type sessionData struct {
|
||||
UserID string `json:"user_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Create(ctx context.Context, tokenHash []byte, userID string, sessionTTL time.Duration) (*model.Session, error) {
|
||||
key := "session:" + hex.EncodeToString(tokenHash)
|
||||
now := time.Now().UTC()
|
||||
data := sessionData{
|
||||
UserID: userID,
|
||||
CreatedAt: now,
|
||||
ExpiresAt: now.Add(sessionTTL),
|
||||
}
|
||||
value, err := json.Marshal(data)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: encoding session %v", repository.ErrDatabase, err)
|
||||
|
||||
}
|
||||
|
||||
err = r.client.Set(ctx, key, value, sessionTTL).Err()
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
session := &model.Session{
|
||||
TokenHash: tokenHash,
|
||||
UserID: data.UserID,
|
||||
CreatedAt: data.CreatedAt,
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
RevokedAt: nil,
|
||||
}
|
||||
|
||||
return session, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *SessionRepository) GetSessionByTokenHash(ctx context.Context, tokenHash []byte) (*model.Session, error) {
|
||||
key := "session:" + hex.EncodeToString(tokenHash)
|
||||
|
||||
value, err := r.client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
var data sessionData
|
||||
|
||||
err = json.Unmarshal([]byte(value), &data)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: decode session %v", repository.ErrDatabase, err)
|
||||
|
||||
}
|
||||
|
||||
session := &model.Session{
|
||||
TokenHash: tokenHash,
|
||||
UserID: data.UserID,
|
||||
CreatedAt: data.CreatedAt,
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
RevokedAt: nil,
|
||||
}
|
||||
|
||||
return session, nil
|
||||
}
|
||||
func (r *SessionRepository) RevokeSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (int, error) {
|
||||
key := "session:" + hex.EncodeToString(tokenHash)
|
||||
|
||||
conn := r.client.Conn()
|
||||
defer conn.Close()
|
||||
|
||||
deleted, err := conn.Del(ctx, key).Result()
|
||||
if err != nil {
|
||||
return 0, convertDBError(err)
|
||||
|
||||
}
|
||||
|
||||
result, err := conn.Do(ctx, "WAITAOF", 1, 0, 2000).Slice()
|
||||
if err != nil {
|
||||
return 0, convertDBError(err)
|
||||
|
||||
}
|
||||
|
||||
if len(result) != 2 {
|
||||
return 0, fmt.Errorf(
|
||||
"%w: WAITAOF: expected 2 counters, got %d",
|
||||
repository.ErrDatabase, len(result),
|
||||
)
|
||||
}
|
||||
|
||||
local, ok := result[0].(int64)
|
||||
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("%w: expected int64, got %T", repository.ErrDatabase, result[0])
|
||||
}
|
||||
if local != 1 {
|
||||
return 0, fmt.Errorf("%w: WAITAOF expected local fsync = 1, got %d", repository.ErrServiceUnavailable, local)
|
||||
}
|
||||
|
||||
return int(deleted), nil
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SessionRepository interface {
|
||||
Create(ctx context.Context, tokenHash []byte, userID string, sessionTTL time.Duration) (*model.Session, error)
|
||||
GetSessionByTokenHash(ctx context.Context, tokenHash []byte) (*model.Session, error)
|
||||
RevokeSession(ctx context.Context, tokenHash []byte) (int, error)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
)
|
||||
|
||||
type UserRepository interface {
|
||||
Create(ctx context.Context, username, displayName string, passwordHash string) (*model.User, error)
|
||||
GetUserByID(ctx context.Context, id string) (*model.User, error)
|
||||
GetUserByUsername(ctx context.Context, username string) (*model.User, error)
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
memory = 64 * 1024
|
||||
iterations = 3
|
||||
parallelism = 2
|
||||
saltLength = 16
|
||||
hashLength = 32
|
||||
)
|
||||
|
||||
var ErrInvalidHash = errors.New("invalid password hash")
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
|
||||
salt := make([]byte, saltLength)
|
||||
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
encodedSalt := base64.RawStdEncoding.EncodeToString(salt)
|
||||
|
||||
hash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
iterations,
|
||||
memory,
|
||||
parallelism,
|
||||
hashLength,
|
||||
)
|
||||
|
||||
encodedHash := base64.RawStdEncoding.EncodeToString(hash)
|
||||
|
||||
hashPassword := fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
memory,
|
||||
iterations,
|
||||
parallelism,
|
||||
encodedSalt,
|
||||
encodedHash,
|
||||
)
|
||||
|
||||
return hashPassword, nil
|
||||
|
||||
}
|
||||
|
||||
func VerifyPassword(password, encodedHash string) (bool, error) {
|
||||
parts := strings.Split(encodedHash, "$")
|
||||
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
versionStr, ok := strings.CutPrefix(parts[2], "v=")
|
||||
if !ok {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
version, err := strconv.ParseUint(versionStr, 10, 32)
|
||||
if err != nil || version != uint64(argon2.Version) {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
params := strings.Split(parts[3], ",")
|
||||
if len(params) != 3 {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
parseParam := func(value, prefix string, bits int) (uint64, error) {
|
||||
number, ok := strings.CutPrefix(value, prefix)
|
||||
if !ok {
|
||||
return 0, ErrInvalidHash
|
||||
}
|
||||
|
||||
return strconv.ParseUint(number, 10, bits)
|
||||
}
|
||||
|
||||
m, err := parseParam(params[0], "m=", 32)
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
t, err := parseParam(params[1], "t=", 32)
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
p, err := parseParam(params[2], "p=", 8)
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
memory := uint32(m)
|
||||
iterations := uint32(t)
|
||||
parallelism := uint8(p)
|
||||
|
||||
if memory < 8*uint32(parallelism) ||
|
||||
memory > 256*1024 ||
|
||||
iterations < 1 || iterations > 10 ||
|
||||
parallelism < 1 || parallelism > 8 {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
if len(salt) != saltLength {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
expectedHash, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
if len(expectedHash) != hashLength {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
computedHash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
iterations,
|
||||
memory,
|
||||
parallelism,
|
||||
uint32(len(expectedHash)),
|
||||
)
|
||||
|
||||
return subtle.ConstantTimeCompare(computedHash, expectedHash) == 1, nil
|
||||
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/security"
|
||||
"time"
|
||||
)
|
||||
|
||||
const tokenType = "Bearer"
|
||||
|
||||
type AuthService struct {
|
||||
userRepo repository.UserRepository
|
||||
sessionRepo repository.SessionRepository
|
||||
sessionTTL time.Duration
|
||||
}
|
||||
|
||||
func NewAuthService(userRepo repository.UserRepository, sessionRepo repository.SessionRepository, sessionTTL time.Duration) *AuthService {
|
||||
return &AuthService{
|
||||
userRepo: userRepo,
|
||||
sessionRepo: sessionRepo,
|
||||
sessionTTL: sessionTTL,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AuthService) Authenticate(ctx context.Context, username, password string) (*model.User, error) {
|
||||
|
||||
userOK := checkUsername(username)
|
||||
passwordOK := checkPassword(password)
|
||||
|
||||
if !userOK || !passwordOK {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
user, err := s.userRepo.GetUserByUsername(ctx, username)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
isVerify, err := security.VerifyPassword(password, user.PasswordHash)
|
||||
|
||||
if err != nil {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
|
||||
if !isVerify {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type CreatedSession struct {
|
||||
Token string
|
||||
TokenType string
|
||||
ExpiresAt time.Time
|
||||
User *model.User
|
||||
}
|
||||
|
||||
func (s *AuthService) CreateSession(ctx context.Context, username, password string) (*CreatedSession, error) {
|
||||
user, err := s.Authenticate(ctx, username, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if s.sessionTTL <= 0 {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
|
||||
tokenBytes := make([]byte, 32)
|
||||
_, err = rand.Read(tokenBytes)
|
||||
if err != nil {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
|
||||
token := base64.RawURLEncoding.EncodeToString(tokenBytes)
|
||||
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
|
||||
session, err := s.sessionRepo.Create(ctx, tokenHash[:], user.ID, s.sessionTTL)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
createdSession := &CreatedSession{
|
||||
Token: token,
|
||||
TokenType: tokenType,
|
||||
ExpiresAt: session.ExpiresAt,
|
||||
User: user,
|
||||
}
|
||||
|
||||
return createdSession, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *AuthService) ValidateSession(ctx context.Context, token string) (string, error) {
|
||||
|
||||
if token == "" {
|
||||
return "", ErrUnauthorized
|
||||
}
|
||||
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
|
||||
session, err := s.sessionRepo.GetSessionByTokenHash(ctx, tokenHash[:])
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return "", ErrUnauthorized
|
||||
}
|
||||
return "", convertRepoError(err)
|
||||
}
|
||||
|
||||
if session.RevokedAt != nil {
|
||||
return "", ErrUnauthorized
|
||||
}
|
||||
|
||||
if !time.Now().Before(session.ExpiresAt) {
|
||||
return "", ErrUnauthorized
|
||||
}
|
||||
|
||||
return session.UserID, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) RevokeSession(ctx context.Context, token string) error {
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
|
||||
_, err := s.sessionRepo.RevokeSession(ctx, tokenHash[:])
|
||||
|
||||
if err != nil {
|
||||
return convertRepoError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type ChatService struct {
|
||||
repo repository.ChatRepository
|
||||
userRepo repository.UserRepository
|
||||
userService *UserService
|
||||
}
|
||||
|
||||
func NewChatService(repo repository.ChatRepository, userRepo repository.UserRepository, userService *UserService) *ChatService {
|
||||
return &ChatService{repo: repo, userRepo: userRepo, userService: userService}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, title string, memberIDs []string, userID string) (*model.Chat, error) {
|
||||
|
||||
trimTitle := strings.TrimSpace(title)
|
||||
|
||||
lenTitle := utf8.RuneCountInString(title)
|
||||
if lenTitle < 1 || lenTitle > 100 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if trimTitle == "" {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if memberIDs == nil || len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{})
|
||||
for _, memberID := range memberIDs {
|
||||
parsedID, err := uuid.Parse(memberID)
|
||||
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
normalizedID := parsedID.String()
|
||||
|
||||
if _, exist := seen[normalizedID]; exist {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
seen[normalizedID] = struct{}{}
|
||||
|
||||
_, err = s.userRepo.GetUserByID(ctx, memberID)
|
||||
if err != nil {
|
||||
// NOTE: MemberNotFound –> InvalidInput
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
}
|
||||
|
||||
parsedUserID, err := uuid.Parse(userID)
|
||||
if err != nil {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
normalizedUserID := parsedUserID.String()
|
||||
|
||||
_, creatorExists := seen[normalizedUserID]
|
||||
if !creatorExists {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
chat, err := s.repo.CreateChat(ctx, title, memberIDs)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) GetChatsByUserID(ctx context.Context, userID string, limit *int, cursor *string) ([]*model.Chat, *string, error) {
|
||||
|
||||
actualLimit := 50
|
||||
|
||||
if limit != nil {
|
||||
actualLimit = *limit
|
||||
}
|
||||
|
||||
if actualLimit <= 0 || actualLimit > 100 {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
var chatPosition *repository.ChatPosition
|
||||
|
||||
if cursor != nil {
|
||||
chCursor, err := decodeCursor[chatCursor](*cursor)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
_, err = uuid.Parse(chCursor.ChatID)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if chCursor.CreatedAt.IsZero() {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
_, err = uuid.Parse(chCursor.UserID)
|
||||
if err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if chCursor.UserID != userID {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
chatPosition = &repository.ChatPosition{
|
||||
CreatedAt: chCursor.CreatedAt,
|
||||
ID: chCursor.ChatID,
|
||||
}
|
||||
}
|
||||
|
||||
chats, err := s.repo.GetChatsByUserID(ctx, userID, actualLimit+1, chatPosition)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
var chCursor *chatCursor
|
||||
|
||||
if len(chats) > actualLimit {
|
||||
chCursor = &chatCursor{
|
||||
ChatID: chats[actualLimit-1].ID,
|
||||
UserID: userID,
|
||||
CreatedAt: chats[actualLimit-1].CreatedAt,
|
||||
}
|
||||
cursor, err = encodeCursor[chatCursor](*chCursor)
|
||||
if err != nil {
|
||||
return nil, nil, ErrServerError
|
||||
}
|
||||
|
||||
return chats[:actualLimit], cursor, nil
|
||||
}
|
||||
|
||||
return chats, nil, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *ChatService) GetChatByID(ctx context.Context, chatID, userID string) (*model.Chat, error) {
|
||||
|
||||
_, err := uuid.Parse(chatID)
|
||||
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
chat, err := s.repo.GetChatByID(ctx, chatID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
index := slices.Index(chat.MemberIDs, userID)
|
||||
|
||||
if index == -1 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
type chatCursor struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ChatID string `json:"chat_id"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"highload/internal/repository"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrAlreadyExists = errors.New("user already exists")
|
||||
ErrNotFound = errors.New("user not found")
|
||||
ErrServerError = errors.New("server error")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrServiceUnavailable = errors.New("service unavailable")
|
||||
ErrConflict = errors.New("data conflict")
|
||||
)
|
||||
|
||||
func convertRepoError(err error) error {
|
||||
|
||||
var category error
|
||||
|
||||
switch {
|
||||
|
||||
case errors.Is(err, repository.ErrNotFound):
|
||||
category = ErrNotFound
|
||||
case errors.Is(err, repository.ErrAlreadyExists):
|
||||
category = ErrAlreadyExists
|
||||
case errors.Is(err, repository.ErrInvalidInput):
|
||||
category = ErrInvalidInput
|
||||
case errors.Is(err, repository.ErrDatabase):
|
||||
category = ErrServerError
|
||||
case errors.Is(err, repository.ErrServiceUnavailable):
|
||||
category = ErrServiceUnavailable
|
||||
case errors.Is(err, repository.ErrConflict):
|
||||
category = ErrConflict
|
||||
default:
|
||||
return err
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %v", category, err)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json/v2"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func encodeCursor[C any](cursor C) (*string, error) {
|
||||
data, err := json.Marshal(cursor)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encoded := base64.RawURLEncoding.EncodeToString(data)
|
||||
|
||||
return &encoded, nil
|
||||
|
||||
}
|
||||
|
||||
func decodeCursor[C any](cursor string) (*C, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
var decoded C
|
||||
|
||||
err = json.Unmarshal(data, &decoded)
|
||||
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
return &decoded, nil
|
||||
}
|
||||
|
||||
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func checkUsername(username string) bool {
|
||||
return usernameRegex.MatchString(username)
|
||||
}
|
||||
|
||||
func checkPassword(password string) bool {
|
||||
|
||||
if !utf8.ValidString(password) {
|
||||
return false
|
||||
}
|
||||
|
||||
if strings.TrimSpace(password) == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
passwordLength := utf8.RuneCountInString(password)
|
||||
if passwordLength < 12 || passwordLength > 128 {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type MessageService struct {
|
||||
repo repository.MessageRepository
|
||||
userService *UserService
|
||||
chatService *ChatService
|
||||
}
|
||||
|
||||
func NewMessageService(repo repository.MessageRepository, chatService *ChatService, userService *UserService) *MessageService {
|
||||
return &MessageService{repo: repo, chatService: chatService, userService: userService}
|
||||
}
|
||||
|
||||
func (s *MessageService) CreateMessage(ctx context.Context, text, chatID, userID, key string) (*model.Message, error) {
|
||||
|
||||
_, err := s.chatService.GetChatByID(ctx, chatID, userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lenText := utf8.RuneCountInString(text)
|
||||
|
||||
if lenText > 4000 || lenText < 1 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
trimText := strings.TrimSpace(text)
|
||||
if len(trimText) == 0 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
message, err := s.repo.CreateMessage(ctx, chatID, userID, text, key)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *MessageService) GetMessagesByChatID(ctx context.Context, chatID, userID string, limit *int, cursor *string) ([]*model.Message, *string, error) {
|
||||
|
||||
actualLimit := 50
|
||||
|
||||
if limit != nil {
|
||||
actualLimit = *limit
|
||||
}
|
||||
|
||||
if actualLimit <= 0 || actualLimit > 100 {
|
||||
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
chat, err := s.chatService.GetChatByID(ctx, chatID, userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var messagePosition *repository.MessagePosition
|
||||
|
||||
if cursor != nil {
|
||||
mesCursor, err := decodeCursor[messageCursor](*cursor)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if _, err := uuid.Parse(mesCursor.ChatID); err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if _, err := uuid.Parse(mesCursor.MessageID); err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if mesCursor.CreatedAt.IsZero() {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if mesCursor.ChatID != chat.ID {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
messagePosition = &repository.MessagePosition{
|
||||
ID: mesCursor.MessageID,
|
||||
CreatedAt: mesCursor.CreatedAt,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
messages, err := s.repo.GetMessagesByChatID(ctx, chat.ID, actualLimit+1, messagePosition)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
if len(messages) > actualLimit {
|
||||
mesCursor := &messageCursor{
|
||||
MessageID: messages[actualLimit-1].ID,
|
||||
ChatID: chat.ID,
|
||||
CreatedAt: messages[actualLimit-1].CreatedAt,
|
||||
}
|
||||
cursor, err = encodeCursor[messageCursor](*mesCursor)
|
||||
if err != nil {
|
||||
return nil, nil, ErrServerError
|
||||
}
|
||||
return messages[:actualLimit], cursor, nil
|
||||
}
|
||||
|
||||
return messages, nil, nil
|
||||
|
||||
}
|
||||
|
||||
type messageCursor struct {
|
||||
MessageID string `json:"message_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/security"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
repo repository.UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(repo repository.UserRepository) *UserService {
|
||||
return &UserService{repo}
|
||||
}
|
||||
|
||||
func (s *UserService) CreateUser(ctx context.Context, username, displayName, password string) (*model.User, error) {
|
||||
|
||||
userOK := checkUsername(username)
|
||||
passwordOK := checkPassword(password)
|
||||
|
||||
if !userOK || !passwordOK {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if !utf8.ValidString(displayName) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if strings.TrimSpace(displayName) == "" {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if utf8.RuneCountInString(displayName) > 100 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
passwordHash, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
|
||||
user, err := s.repo.Create(ctx, username, displayName, passwordHash)
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *UserService) GetUser(ctx context.Context, id string) (*model.User, error) {
|
||||
|
||||
_, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
user, err := s.repo.GetUserByID(ctx, id)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
authService *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{authService: authService}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
|
||||
if !ok {
|
||||
httputils.WriteBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
var probe [1]byte
|
||||
|
||||
n, err := r.Body.Read(probe[:])
|
||||
|
||||
if n > 0 || (err != nil && !errors.Is(err, io.EOF)) {
|
||||
_ = httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
|
||||
Code: "invalid_request",
|
||||
Message: "Request body must be empty",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
createdSession, err := h.authService.CreateSession(r.Context(), username, password)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httputils.WriteBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := createSessionResponse{
|
||||
Token: createdSession.Token,
|
||||
TokenType: createdSession.TokenType,
|
||||
ExpiresAt: httputils.FormatTime(createdSession.ExpiresAt),
|
||||
User: UserResponse{
|
||||
Username: createdSession.User.Username,
|
||||
ID: createdSession.User.ID,
|
||||
DisplayName: createdSession.User.DisplayName,
|
||||
CreatedAt: httputils.FormatTime(createdSession.User.CreatedAt),
|
||||
},
|
||||
}
|
||||
|
||||
httputils.WriteJSON[createSessionResponse](w, http.StatusCreated, response)
|
||||
|
||||
}
|
||||
|
||||
func (h *AuthHandler) DeleteSession(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
token, ok := httputils.ExtractBearerToken(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
err := h.authService.RevokeSession(r.Context(), token)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package handler
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type createSessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chatService *service.ChatService
|
||||
}
|
||||
|
||||
func NewChatHandler(chatService *service.ChatService) *ChatHandler {
|
||||
return &ChatHandler{chatService: chatService}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
req, code := httputils.Decode[chatCreateRequest](r)
|
||||
|
||||
if code != http.StatusOK {
|
||||
if code == http.StatusUnsupportedMediaType {
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.chatService.Create(r.Context(), req.Title, req.MemberIDs, userID)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := chatResponse{
|
||||
Title: result.Title,
|
||||
MemberIDs: result.MemberIDs,
|
||||
ID: result.ID,
|
||||
CreatedAt: httputils.FormatTime(result.CreatedAt),
|
||||
}
|
||||
|
||||
_ = httputils.WriteJSON[chatResponse](w, http.StatusCreated, response)
|
||||
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetChatsByUserID(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
limit, cursor, ok := httputils.GetLimitAndCursor(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
chats, nextCursor, err := h.chatService.GetChatsByUserID(r.Context(), userID, limit, cursor)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
chatResponses := make([]chatResponse, len(chats))
|
||||
for index, chat := range chats {
|
||||
chatResponses[index] = *convertChatModelToResponse(chat)
|
||||
}
|
||||
|
||||
response := chatGetByUserIDResponse{
|
||||
Items: chatResponses,
|
||||
NextCursor: nextCursor,
|
||||
}
|
||||
|
||||
_ = httputils.WriteJSON[chatGetByUserIDResponse](w, http.StatusOK, response)
|
||||
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetChatByChatID(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
chat, err := h.chatService.GetChatByID(r.Context(), chatID, userID)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertChatModelToResponse(chat)
|
||||
_ = httputils.WriteJSON[chatResponse](w, http.StatusOK, *response)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/model"
|
||||
"highload/internal/transport/http/httputils"
|
||||
)
|
||||
|
||||
type chatCreateRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type chatResponse struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
ID string `json:"id"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatGetByUserIDResponse struct {
|
||||
Items []chatResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func convertChatModelToResponse(model *model.Chat) *chatResponse {
|
||||
return &chatResponse{
|
||||
Title: model.Title,
|
||||
ID: model.ID,
|
||||
MemberIDs: model.MemberIDs,
|
||||
CreatedAt: httputils.FormatTime(model.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type HealthHandler struct {
|
||||
pool *pgxpool.Pool
|
||||
redisClient *redis.Client
|
||||
}
|
||||
|
||||
func NewHealthHandler(pool *pgxpool.Pool, redisClient *redis.Client) *HealthHandler {
|
||||
return &HealthHandler{pool: pool, redisClient: redisClient}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
|
||||
response := HealthResponse{Status: "ok"}
|
||||
err := httputils.WriteJSON[HealthResponse](w, http.StatusOK, response)
|
||||
if err != nil {
|
||||
slog.Error("failed to write health response", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
if err := h.pool.Ping(ctx); err != nil {
|
||||
slog.Error("database readiness check failed", "error", err)
|
||||
if writeErr := httputils.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
httputils.ErrorDetails{
|
||||
Message: "unavailable",
|
||||
Code: "unavailable",
|
||||
RequestID: requestID,
|
||||
},
|
||||
); writeErr != nil {
|
||||
slog.Error("failed to write readiness response", "error", writeErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.redisClient.Ping(ctx).Err(); err != nil {
|
||||
slog.Error("redis readiness check failed", "error", err)
|
||||
if writeErr := httputils.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
httputils.ErrorDetails{
|
||||
Message: "unavailable",
|
||||
Code: "unavailable",
|
||||
RequestID: requestID,
|
||||
},
|
||||
); writeErr != nil {
|
||||
slog.Error("failed to write readiness response", "error", writeErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
response := HealthResponse{Status: "ok"}
|
||||
err := httputils.WriteJSON[HealthResponse](w, http.StatusOK, response)
|
||||
if err != nil {
|
||||
slog.Error("failed to write health response", "error", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (h *HealthHandler) NotFoundRoute(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
err := httputils.WriteError(
|
||||
w,
|
||||
http.StatusNotFound,
|
||||
httputils.ErrorDetails{
|
||||
Code: "not_found",
|
||||
Message: "Not Found",
|
||||
RequestID: requestID,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
slog.Error("failed to write not found response", "error", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package handler
|
||||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type MessageHandler struct {
|
||||
messageService *service.MessageService
|
||||
}
|
||||
|
||||
func NewMessageHandler(messageService *service.MessageService) *MessageHandler {
|
||||
return &MessageHandler{messageService: messageService}
|
||||
}
|
||||
|
||||
func (h *MessageHandler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
req, code := httputils.Decode[messageCreateRequest](r)
|
||||
|
||||
if code != http.StatusOK {
|
||||
if code == http.StatusUnsupportedMediaType {
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
|
||||
if ok := httputils.CheckIdempotencyKeyPattern(key); !ok {
|
||||
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
|
||||
Code: "invalid_request",
|
||||
Message: "wrong Idempotency-Key",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := h.messageService.CreateMessage(r.Context(), req.Text, chatID, userID, key)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertMessageModelToResponse(message)
|
||||
|
||||
_ = httputils.WriteJSON[messageResponse](w, http.StatusCreated, *response)
|
||||
|
||||
}
|
||||
|
||||
func (h *MessageHandler) GetMessagesByChatID(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
limit, cursor, ok := httputils.GetLimitAndCursor(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
messages, nextCursor, err := h.messageService.GetMessagesByChatID(r.Context(), chatID, userID, limit, cursor)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
messageResponses := make([]messageResponse, len(messages))
|
||||
for index, message := range messages {
|
||||
messageResponses[index] = *convertMessageModelToResponse(message)
|
||||
}
|
||||
|
||||
response := messageGetResponse{
|
||||
Items: messageResponses,
|
||||
NextCursor: nextCursor,
|
||||
}
|
||||
|
||||
_ = httputils.WriteJSON[messageGetResponse](w, http.StatusOK, response)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/model"
|
||||
"highload/internal/transport/http/httputils"
|
||||
)
|
||||
|
||||
type messageCreateRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type messageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type messageGetResponse struct {
|
||||
Items []messageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func convertMessageModelToResponse(message *model.Message) *messageResponse {
|
||||
return &messageResponse{
|
||||
ID: message.ID,
|
||||
ChatID: message.ChatID,
|
||||
SenderID: message.SenderID,
|
||||
Text: message.Text,
|
||||
CreatedAt: httputils.FormatTime(message.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
userService *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(service *service.UserService) *UserHandler {
|
||||
return &UserHandler{userService: service}
|
||||
}
|
||||
|
||||
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
req, code := httputils.Decode[userCreateRequest](r)
|
||||
|
||||
if code != http.StatusOK {
|
||||
if code == http.StatusUnsupportedMediaType {
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.userService.CreateUser(r.Context(), req.Username, req.DisplayName, req.Password)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertUserModelToResponse(user)
|
||||
|
||||
_ = httputils.WriteJSON[userResponse](w, http.StatusCreated, *response)
|
||||
|
||||
}
|
||||
|
||||
func (h *UserHandler) GetCurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
user, err := h.userService.GetUser(r.Context(), userID)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertUserModelToResponse(user)
|
||||
|
||||
_ = httputils.WriteJSON[userResponse](w, http.StatusOK, *response)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/model"
|
||||
"highload/internal/transport/http/httputils"
|
||||
)
|
||||
|
||||
type userCreateRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type userResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func convertUserModelToResponse(user *model.User) *userResponse {
|
||||
return &userResponse{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: httputils.FormatTime(user.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package httputils
|
||||
|
||||
import (
|
||||
"encoding/json/v2"
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error ErrorDetails `json:"error"`
|
||||
}
|
||||
|
||||
type ErrorDetails struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
func Decode[T any](r *http.Request) (*T, int) {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return nil, http.StatusUnsupportedMediaType
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
|
||||
if !utf8.Valid(body) {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
|
||||
req := new(T)
|
||||
|
||||
err = json.Unmarshal(body, req, json.RejectUnknownMembers(true))
|
||||
if err != nil {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
return req, http.StatusOK
|
||||
|
||||
}
|
||||
|
||||
func GetLimitAndCursor(r *http.Request) (limit *int, cursor *string, ok bool) {
|
||||
query := r.URL.Query()
|
||||
|
||||
var currentLimit *int
|
||||
|
||||
if query.Has("limit") {
|
||||
limitStr := query.Get("limit")
|
||||
|
||||
if limitStr == "" {
|
||||
return nil, nil, false
|
||||
}
|
||||
limitInt, err := strconv.Atoi(limitStr)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
currentLimit = &limitInt
|
||||
|
||||
}
|
||||
|
||||
var currentCursor *string
|
||||
if query.Has("cursor") {
|
||||
cursor := query.Get("cursor")
|
||||
currentCursor = &cursor
|
||||
}
|
||||
|
||||
return currentLimit, currentCursor, true
|
||||
}
|
||||
|
||||
func WriteJSON[T any](w http.ResponseWriter, status int, response T) error {
|
||||
data, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_, err = w.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func ErrorFromService(err error) (int, string) {
|
||||
|
||||
switch {
|
||||
case errors.Is(err, service.ErrInvalidInput):
|
||||
return http.StatusBadRequest, "invalid_request"
|
||||
|
||||
case errors.Is(err, service.ErrNotFound):
|
||||
return http.StatusNotFound, "not_found"
|
||||
|
||||
case errors.Is(err, service.ErrAlreadyExists):
|
||||
return http.StatusConflict, "conflict"
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
return http.StatusUnauthorized, "unauthorized"
|
||||
case errors.Is(err, service.ErrServiceUnavailable):
|
||||
return http.StatusServiceUnavailable, "unavailable"
|
||||
case errors.Is(err, service.ErrConflict):
|
||||
return http.StatusConflict, "conflict"
|
||||
default:
|
||||
return http.StatusInternalServerError, "internal_error"
|
||||
}
|
||||
}
|
||||
|
||||
func WriteBasicUnauthorized(w http.ResponseWriter, requestID string) error {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Basic realm="messenger", charset="UTF-8"`,
|
||||
)
|
||||
|
||||
return WriteError(w, http.StatusUnauthorized, ErrorDetails{
|
||||
Code: "unauthorized",
|
||||
Message: "Unauthorized",
|
||||
RequestID: requestID,
|
||||
})
|
||||
}
|
||||
|
||||
func WriteBearerUnauthorized(w http.ResponseWriter, requestID string) error {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Bearer realm="messenger"`,
|
||||
)
|
||||
|
||||
return WriteError(w, http.StatusUnauthorized, ErrorDetails{
|
||||
Code: "unauthorized",
|
||||
Message: "Unauthorized",
|
||||
RequestID: requestID,
|
||||
})
|
||||
}
|
||||
|
||||
func WriteError(w http.ResponseWriter, code int, errorDetails ErrorDetails) error {
|
||||
return WriteJSON(w, code, ErrorResponse{Error: errorDetails})
|
||||
|
||||
}
|
||||
func WriteServiceError(w http.ResponseWriter, err error, requestID string) error {
|
||||
status, code := ErrorFromService(err)
|
||||
|
||||
if status >= http.StatusInternalServerError {
|
||||
slog.Error("request failed",
|
||||
"error", err,
|
||||
"request_id", requestID,
|
||||
"status", status,
|
||||
"code", code,
|
||||
)
|
||||
}
|
||||
|
||||
return WriteJSON(w, status, ErrorResponse{
|
||||
Error: ErrorDetails{
|
||||
Code: code,
|
||||
Message: http.StatusText(status),
|
||||
RequestID: requestID,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func ExtractBearerToken(r *http.Request) (string, bool) {
|
||||
scheme, token, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
if !ok ||
|
||||
!strings.EqualFold(scheme, "Bearer") ||
|
||||
token == "" ||
|
||||
strings.ContainsAny(token, " \t\r\n") {
|
||||
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func FormatTime(t time.Time) string {
|
||||
return t.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
|
||||
func CheckIdempotencyKeyPattern(key string) bool {
|
||||
patternReg := regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
return patternReg.MatchString(key)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Middleware struct {
|
||||
authService *service.AuthService
|
||||
instanceID string
|
||||
}
|
||||
|
||||
func NewMiddleware(authService *service.AuthService, instanceID string) *Middleware {
|
||||
|
||||
return &Middleware{
|
||||
authService: authService,
|
||||
instanceID: instanceID,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (m *Middleware) Auth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := RequestIDFromContext(r.Context())
|
||||
|
||||
token, ok := httputils.ExtractBearerToken(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := m.authService.ValidateSession(r.Context(), token)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := WithUserID(r.Context(), userID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Middleware) RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := uuid.NewString()
|
||||
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
|
||||
ctx := WithRequestID(r.Context(), requestID)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Middleware) InstanceID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", m.instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package middleware
|
||||
|
||||
import "context"
|
||||
|
||||
// UserID
|
||||
type contextKey string
|
||||
|
||||
const userIDKey contextKey = "userID"
|
||||
|
||||
func WithUserID(ctx context.Context, userID string) context.Context {
|
||||
return context.WithValue(ctx, userIDKey, userID)
|
||||
}
|
||||
|
||||
func UserIDFromContext(ctx context.Context) string {
|
||||
userID, _ := ctx.Value(userIDKey).(string)
|
||||
return userID
|
||||
}
|
||||
|
||||
// RequestIDKey
|
||||
const requestIDKey contextKey = "requestID"
|
||||
|
||||
func RequestIDFromContext(ctx context.Context) string {
|
||||
requestID, _ := ctx.Value(requestIDKey).(string)
|
||||
return requestID
|
||||
}
|
||||
|
||||
func WithRequestID(ctx context.Context, requestID string) context.Context {
|
||||
return context.WithValue(ctx, requestIDKey, requestID)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type responseWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *responseWriter) WriteHeader(status int) {
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (m *Middleware) Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
rw := &responseWriter{
|
||||
ResponseWriter: w,
|
||||
status: http.StatusOK,
|
||||
}
|
||||
|
||||
next.ServeHTTP(rw, r)
|
||||
|
||||
slog.Info(
|
||||
"http request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", rw.status,
|
||||
"duration", time.Since(start),
|
||||
"request_id", RequestIDFromContext(r.Context()),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Router struct {
|
||||
middleware *middleware.Middleware
|
||||
authHandler *handler.AuthHandler
|
||||
healthHandler *handler.HealthHandler
|
||||
chatHandler *handler.ChatHandler
|
||||
userHandler *handler.UserHandler
|
||||
messageHandler *handler.MessageHandler
|
||||
}
|
||||
|
||||
func NewRouter(middleware *middleware.Middleware, authHandler *handler.AuthHandler, healthHandler *handler.HealthHandler, chatHandler *handler.ChatHandler, userHandler *handler.UserHandler, messageHandler *handler.MessageHandler) *Router {
|
||||
return &Router{chatHandler: chatHandler, authHandler: authHandler, healthHandler: healthHandler, middleware: middleware, userHandler: userHandler, messageHandler: messageHandler}
|
||||
}
|
||||
|
||||
func (r *Router) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
protectedMux := http.NewServeMux()
|
||||
|
||||
protectedMux.HandleFunc("/", r.healthHandler.NotFoundRoute)
|
||||
mux.HandleFunc("GET /health/live", r.healthHandler.Live)
|
||||
mux.HandleFunc("GET /health/ready", r.healthHandler.Ready)
|
||||
|
||||
//Auth
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", r.authHandler.CreateSession)
|
||||
protectedMux.HandleFunc("DELETE /api/v1/auth/sessions/current", r.authHandler.DeleteSession)
|
||||
|
||||
//User
|
||||
mux.HandleFunc("POST /api/v1/users", r.userHandler.CreateUser)
|
||||
protectedMux.HandleFunc("GET /api/v1/users/me", r.userHandler.GetCurrentUser)
|
||||
|
||||
//Chat
|
||||
protectedMux.HandleFunc("POST /api/v1/chats", r.chatHandler.CreateChat)
|
||||
protectedMux.HandleFunc("GET /api/v1/chats", r.chatHandler.GetChatsByUserID)
|
||||
protectedMux.HandleFunc("GET /api/v1/chats/{chat_id}", r.chatHandler.GetChatByChatID)
|
||||
|
||||
//Message
|
||||
protectedMux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", r.messageHandler.CreateMessage)
|
||||
protectedMux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", r.messageHandler.GetMessagesByChatID)
|
||||
|
||||
mux.Handle("/api/v1/", r.middleware.Auth(protectedMux))
|
||||
return r.middleware.InstanceID(r.middleware.RequestID(
|
||||
r.middleware.Logging(mux),
|
||||
))
|
||||
}
|
||||
Reference in New Issue
Block a user