ЛР 4: вложения в S3 и двусторонняя сверка хранилищ

This commit is contained in:
2026-11-15 11:50:57 +03:00
parent ec540a1a72
commit b58e703546
160 changed files with 16598 additions and 25 deletions
+175
View File
@@ -0,0 +1,175 @@
package config
import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
type Database struct {
PostgresURL string
RedisAddr string
}
type S3 struct {
Endpoint string
Region string
Bucket string
AccessKeyID string
SecretAccessKey string
}
type Config struct {
HTTP struct {
Host string
Port string
}
Database Database
Session struct {
TTL time.Duration
Store string
}
S3 S3
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
}
config.S3, err = getS3Data()
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 LoadAttachmentCleanup() (postgresURL string, objectStorage S3, err error) {
postgresURL, err = loadPostgresURL()
if err != nil {
return "", S3{}, err
}
objectStorage, err = getS3Data()
return postgresURL, objectStorage, err
}
func loadPostgresURL() (string, error) {
postgresData, err := os.ReadFile(os.Getenv("DATABASE_URL_FILE"))
if err != nil {
return "", fmt.Errorf("read database URL: %w", err)
}
postgresURL := strings.TrimSpace(string(postgresData))
if postgresURL == "" {
return "", fmt.Errorf("empty database URL")
}
return postgresURL, nil
}
func getDatabaseURL() (Database, error) {
postgresURL, err := loadPostgresURL()
if err != nil {
return Database{}, err
}
db := Database{PostgresURL: postgresURL}
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
}
func getS3Data() (S3, error) {
s3 := S3{
Endpoint: os.Getenv("S3_ENDPOINT"),
Region: os.Getenv("S3_REGION"),
Bucket: os.Getenv("S3_BUCKET"),
}
if s3.Endpoint == "" {
return s3, fmt.Errorf("empty s3 endpoint")
}
if s3.Region == "" {
return s3, fmt.Errorf("empty s3 region")
}
if s3.Bucket == "" {
return s3, fmt.Errorf("emtpy s3 bucket")
}
accessKeyIDPath := os.Getenv("S3_ACCESS_KEY_ID_FILE")
accessKeyID, err := os.ReadFile(accessKeyIDPath)
if err != nil {
return s3, fmt.Errorf("empty s3 access_key_id")
}
s3.AccessKeyID = strings.TrimSpace(string(accessKeyID))
secretAccessKeyPath := os.Getenv("S3_SECRET_ACCESS_KEY_FILE")
secretAccessKey, err := os.ReadFile(secretAccessKeyPath)
if err != nil {
return s3, fmt.Errorf("empty s3 secret_access_key_file")
}
s3.SecretAccessKey = strings.TrimSpace(string(secretAccessKey))
return s3, nil
}
+21
View File
@@ -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
}
+31
View File
@@ -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
}
+207
View File
@@ -0,0 +1,207 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: attachments.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const attachmentExistsByObjectKey = `-- name: AttachmentExistsByObjectKey :one
SELECT EXISTS (
SELECT 1 FROM attachments
WHERE object_key = $1
)
`
func (q *Queries) AttachmentExistsByObjectKey(ctx context.Context, objectKey string) (bool, error) {
row := q.db.QueryRow(ctx, attachmentExistsByObjectKey, objectKey)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const createAttachment = `-- name: CreateAttachment :one
INSERT INTO attachments
(chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, created_at, updated_at
`
type CreateAttachmentParams struct {
ChatID pgtype.UUID
OwnerID pgtype.UUID
Filename string
ObjectKey string
ContentType string
SizeBytes int64
Sha256 string
}
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) {
row := q.db.QueryRow(ctx, createAttachment,
arg.ChatID,
arg.OwnerID,
arg.Filename,
arg.ObjectKey,
arg.ContentType,
arg.SizeBytes,
arg.Sha256,
)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ObjectKey,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getAttachmentByID = `-- name: GetAttachmentByID :one
SELECT id, chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, created_at, updated_at FROM attachments WHERE id = $1
`
func (q *Queries) GetAttachmentByID(ctx context.Context, attachmentID pgtype.UUID) (Attachment, error) {
row := q.db.QueryRow(ctx, getAttachmentByID, attachmentID)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ObjectKey,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getAttachmentForUser = `-- name: GetAttachmentForUser :one
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.object_key, a.content_type, a.size_bytes, a.sha256, a.created_at, a.updated_at
FROM attachments AS a
JOIN chat_members AS cm ON cm.chat_id = a.chat_id
WHERE a.id = $1
AND cm.user_id = $2
`
type GetAttachmentForUserParams struct {
AttachmentID pgtype.UUID
UserID pgtype.UUID
}
func (q *Queries) GetAttachmentForUser(ctx context.Context, arg GetAttachmentForUserParams) (Attachment, error) {
row := q.db.QueryRow(ctx, getAttachmentForUser, arg.AttachmentID, arg.UserID)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ObjectKey,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getAttachmentsForMessages = `-- name: GetAttachmentsForMessages :many
SELECT message_id, attachment_id, position
FROM messages_attachments
WHERE message_id = ANY($1::uuid[])
ORDER BY message_id, position
`
type GetAttachmentsForMessagesRow struct {
MessageID pgtype.UUID
AttachmentID pgtype.UUID
Position int16
}
func (q *Queries) GetAttachmentsForMessages(ctx context.Context, messageIds []pgtype.UUID) ([]GetAttachmentsForMessagesRow, error) {
rows, err := q.db.Query(ctx, getAttachmentsForMessages, messageIds)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetAttachmentsForMessagesRow
for rows.Next() {
var i GetAttachmentsForMessagesRow
if err := rows.Scan(&i.MessageID, &i.AttachmentID, &i.Position); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAttachmentKeys = `-- name: ListAttachmentKeys :many
SELECT id, object_key, created_at
FROM attachments
WHERE object_key > $1
ORDER BY object_key
LIMIT $2
`
type ListAttachmentKeysParams struct {
AfterKey string
PageSize int32
}
type ListAttachmentKeysRow struct {
ID pgtype.UUID
ObjectKey string
CreatedAt pgtype.Timestamptz
}
func (q *Queries) ListAttachmentKeys(ctx context.Context, arg ListAttachmentKeysParams) ([]ListAttachmentKeysRow, error) {
rows, err := q.db.Query(ctx, listAttachmentKeys, arg.AfterKey, arg.PageSize)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAttachmentKeysRow
for rows.Next() {
var i ListAttachmentKeysRow
if err := rows.Scan(&i.ID, &i.ObjectKey, &i.CreatedAt); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const tryLockAttachmentObjectKey = `-- name: TryLockAttachmentObjectKey :one
SELECT pg_try_advisory_xact_lock(
hashtextextended($1::text, 0)
)::boolean AS locked
`
func (q *Queries) TryLockAttachmentObjectKey(ctx context.Context, objectKey string) (bool, error) {
row := q.db.QueryRow(ctx, tryLockAttachmentObjectKey, objectKey)
var locked bool
err := row.Scan(&locked)
return locked, err
}
@@ -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
}
+118
View File
@@ -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
}
+32
View File
@@ -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_idempotence.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
}
+91
View File
@@ -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,71 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: messages_attachments.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const createMessagesAttachments = `-- name: CreateMessagesAttachments :execrows
INSERT INTO messages_attachments (message_id, attachment_id, chat_id, position)
SELECT $1, $2, $3, $4
FROM attachments
WHERE id = $2 AND chat_id = $3
`
type CreateMessagesAttachmentsParams struct {
MessageID pgtype.UUID
AttachmentID pgtype.UUID
ChatID pgtype.UUID
Position int16
}
func (q *Queries) CreateMessagesAttachments(ctx context.Context, arg CreateMessagesAttachmentsParams) (int64, error) {
result, err := q.db.Exec(ctx, createMessagesAttachments,
arg.MessageID,
arg.AttachmentID,
arg.ChatID,
arg.Position,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getMessagesAttachments = `-- name: GetMessagesAttachments :many
SELECT attachment_id, position
FROM messages_attachments
WHERE message_id = $1
ORDER BY position ASC
`
type GetMessagesAttachmentsRow struct {
AttachmentID pgtype.UUID
Position int16
}
func (q *Queries) GetMessagesAttachments(ctx context.Context, messageID pgtype.UUID) ([]GetMessagesAttachmentsRow, error) {
rows, err := q.db.Query(ctx, getMessagesAttachments, messageID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetMessagesAttachmentsRow
for rows.Next() {
var i GetMessagesAttachmentsRow
if err := rows.Scan(&i.AttachmentID, &i.Position); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
+65
View File
@@ -0,0 +1,65 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package sqlc
import (
"github.com/jackc/pgx/v5/pgtype"
)
type Attachment struct {
ID pgtype.UUID
ChatID pgtype.UUID
OwnerID pgtype.UUID
Filename string
ObjectKey string
ContentType string
SizeBytes int64
Sha256 string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
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 MessagesAttachment struct {
MessageID pgtype.UUID
AttachmentID pgtype.UUID
ChatID pgtype.UUID
Position int16
}
type User struct {
ID pgtype.UUID
Username string
DisplayName string
PasswordHash string
CreatedAt pgtype.Timestamptz
}
+77
View File
@@ -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
}
+16
View File
@@ -0,0 +1,16 @@
package model
import "time"
type Attachment struct {
ID string
ChatID string
OwnerID string
Filename string
ObjectKey string
ContentType string
SizeBytes int64
SHA256 string
CreatedAt time.Time
UpdatedAt time.Time
}
+10
View File
@@ -0,0 +1,10 @@
package model
import "time"
type Chat struct {
ID string
Title string
MemberIDs []string
CreatedAt time.Time
}
+12
View File
@@ -0,0 +1,12 @@
package model
import "time"
type Message struct {
ID string
ChatID string
SenderID string
Text string
AttachmentIDs []string
CreatedAt time.Time
}
+11
View File
@@ -0,0 +1,11 @@
package model
import "time"
type Session struct {
TokenHash []byte
UserID string
CreatedAt time.Time
ExpiresAt time.Time
RevokedAt *time.Time
}
+11
View File
@@ -0,0 +1,11 @@
package model
import "time"
type User struct {
ID string
Username string
DisplayName string
PasswordHash string
CreatedAt time.Time
}
+36
View File
@@ -0,0 +1,36 @@
package repository
import (
"context"
"highload/internal/model"
"time"
)
type AttachmentRepository interface {
CreateAttachment(ctx context.Context, params CreateAttachmentParams) (*model.Attachment, error)
GetAttachmentForUser(ctx context.Context, userID, attachmentID string) (*model.Attachment, error)
ExistsByObjectKey(ctx context.Context, key string) (bool, error)
WithObjectKeyLock(ctx context.Context, key string, fn func(context.Context, AttachmentTx) error) (bool, error)
}
type AttachmentKey struct {
ID string
ObjectKey string
CreatedAt time.Time
}
type AttachmentReconcileRepository interface {
ListAttachmentKeys(ctx context.Context, afterKey string, pageSize int32) ([]AttachmentKey, error)
GetAttachmentByID(ctx context.Context, id string) (*model.Attachment, error)
WithObjectKeyLock(ctx context.Context, key string, fn func(context.Context, AttachmentTx) error) (bool, error)
}
type CreateAttachmentParams struct {
ChatID string
OwnerID string
Filename string
ObjectKey string
ContentType string
Sha256 string
SizeBytes int64
}
+12
View File
@@ -0,0 +1,12 @@
package repository
import (
"context"
"highload/internal/model"
)
type AttachmentTx interface {
CreateAttachment(ctx context.Context, params CreateAttachmentParams) (*model.Attachment, error)
ExistsByObjectKey(ctx context.Context, key string) (bool, error)
GetAttachmentByID(ctx context.Context, id string) (*model.Attachment, error)
}
+18
View File
@@ -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
}
+16
View File
@@ -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")
)
+17
View File
@@ -0,0 +1,17 @@
package repository
import (
"context"
"highload/internal/model"
"time"
)
type MessageRepository interface {
CreateMessage(ctx context.Context, chatID, senderID, text, key string, attachmentIDs []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
}
+188
View File
@@ -0,0 +1,188 @@
package postgres
import (
"context"
"highload/internal/database/sqlc"
"highload/internal/model"
"highload/internal/repository"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
const attachmentTransactionTimeout = 5 * time.Second
type AttachmentRepository struct {
queries *sqlc.Queries
pool *pgxpool.Pool
}
func NewAttachmentRepository(queries *sqlc.Queries, pool *pgxpool.Pool) *AttachmentRepository {
return &AttachmentRepository{
queries: queries,
pool: pool,
}
}
func (r *AttachmentRepository) CreateAttachment(ctx context.Context, params repository.CreateAttachmentParams) (*model.Attachment, error) {
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
chatUUID, err := getUUIDFromString(params.ChatID)
if err != nil {
return nil, err
}
ownerUUID, err := getUUIDFromString(params.OwnerID)
if err != nil {
return nil, err
}
sqlcParams := sqlc.CreateAttachmentParams{
ChatID: *chatUUID,
OwnerID: *ownerUUID,
Filename: params.Filename,
ObjectKey: params.ObjectKey,
ContentType: params.ContentType,
SizeBytes: params.SizeBytes,
Sha256: params.Sha256,
}
sqlcAttachment, err := r.queries.CreateAttachment(dbCtx, sqlcParams)
if err != nil {
return nil, convertDBError(err)
}
attachment := mapAttachmentSqlcToModel(sqlcAttachment)
return attachment, nil
}
func (r *AttachmentRepository) GetAttachmentForUser(ctx context.Context, userID, attachmentID string) (*model.Attachment, error) {
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
userUUID, err := getUUIDFromString(userID)
if err != nil {
return nil, err
}
attachmentUUID, err := getUUIDFromString(attachmentID)
if err != nil {
return nil, err
}
params := sqlc.GetAttachmentForUserParams{
AttachmentID: *attachmentUUID,
UserID: *userUUID,
}
sqlcAttachment, err := r.queries.GetAttachmentForUser(dbCtx, params)
if err != nil {
return nil, convertDBError(err)
}
attachment := mapAttachmentSqlcToModel(sqlcAttachment)
return attachment, nil
}
func (r *AttachmentRepository) ExistsByObjectKey(ctx context.Context, key string) (bool, error) {
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
exists, err := r.queries.AttachmentExistsByObjectKey(dbCtx, key)
if err != nil {
return false, convertDBError(err)
}
return exists, nil
}
func (r *AttachmentRepository) ListAttachmentKeys(ctx context.Context, afterKey string, pageSize int32) ([]repository.AttachmentKey, error) {
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
rows, err := r.queries.ListAttachmentKeys(dbCtx, sqlc.ListAttachmentKeysParams{AfterKey: afterKey, PageSize: pageSize})
if err != nil {
return nil, convertDBError(err)
}
keys := make([]repository.AttachmentKey, 0, len(rows))
for _, row := range rows {
keys = append(keys, repository.AttachmentKey{
ID: row.ID.String(), ObjectKey: row.ObjectKey, CreatedAt: row.CreatedAt.Time,
})
}
return keys, nil
}
func (r *AttachmentRepository) GetAttachmentByID(ctx context.Context, id string) (*model.Attachment, error) {
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
attachmentID, err := getUUIDFromString(id)
if err != nil {
return nil, err
}
row, err := r.queries.GetAttachmentByID(dbCtx, *attachmentID)
if err != nil {
return nil, convertDBError(err)
}
return mapAttachmentSqlcToModel(row), nil
}
func (r *AttachmentRepository) WithObjectKeyLock(ctx context.Context, key string, fn func(context.Context, repository.AttachmentTx) error) (bool, error) {
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
defer cancel()
tx, err := r.pool.BeginTx(txCtx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
return false, convertDBError(err)
}
defer func() {
rollbackCtx, rollbackCancel := context.WithTimeout(
context.WithoutCancel(ctx),
time.Second,
)
defer rollbackCancel()
_ = tx.Rollback(rollbackCtx)
}()
txQueries := r.queries.WithTx(tx)
locked, err := txQueries.TryLockAttachmentObjectKey(txCtx, key)
if err != nil {
return false, convertDBError(err)
}
if !locked {
return false, nil
}
txRepo := &AttachmentRepository{queries: txQueries}
if err = fn(txCtx, txRepo); err != nil {
return true, err
}
if err = tx.Commit(txCtx); err != nil {
return true, convertDBError(err)
}
return true, nil
}
func mapAttachmentSqlcToModel(sa sqlc.Attachment) *model.Attachment {
return &model.Attachment{
ID: sa.ID.String(),
ChatID: sa.ChatID.String(),
OwnerID: sa.OwnerID.String(),
Filename: sa.Filename,
ObjectKey: sa.ObjectKey,
ContentType: sa.ContentType,
SizeBytes: sa.SizeBytes,
SHA256: sa.Sha256,
CreatedAt: sa.CreatedAt.Time,
UpdatedAt: sa.UpdatedAt.Time,
}
}
+163
View File
@@ -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,
}
}
+46
View File
@@ -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)
}
+205
View File
@@ -0,0 +1,205 @@
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 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, attachmentIDs []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)
}
requestedIDs := make([]string, 0, len(attachmentIDs))
for index, attID := range attachmentIDs {
attUUID, err := getUUIDFromString(attID)
if err != nil {
return nil, convertDBError(err)
}
requestedIDs = append(requestedIDs, attUUID.String())
cmaParams := sqlc.CreateMessagesAttachmentsParams{MessageID: sqlcMessage.ID, AttachmentID: *attUUID, ChatID: sqlcMessage.ChatID, Position: int16(index)}
rowsAffected, err := txQueries.CreateMessagesAttachments(txCtx, cmaParams)
if err != nil {
return nil, convertDBError(err)
}
if rowsAffected == 0 {
return nil, repository.ErrNotFound
}
}
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)
}
resultIDs := requestedIDs
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)
}
rows, err := r.queries.GetMessagesAttachments(dbCtx, sqlcMessage.ID)
if err != nil {
return nil, convertDBError(err)
}
savedIDs := make([]string, 0, len(rows))
for _, row := range rows {
savedIDs = append(savedIDs, row.AttachmentID.String())
}
if sqlcMessage.Text != text || !slices.Equal(savedIDs, requestedIDs) {
return nil, repository.ErrConflict
}
resultIDs = savedIDs
default:
return nil, repository.ErrServerError
}
message := &model.Message{
ID: sqlcMessage.ID.String(),
ChatID: sqlcMessage.ChatID.String(),
SenderID: sqlcMessage.SenderID.String(),
Text: sqlcMessage.Text,
AttachmentIDs: resultIDs,
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)
}
messageIDs := make([]pgtype.UUID, len(sqlcMessages))
for index, _ := range sqlcMessages {
messageIDs[index] = sqlcMessages[index].ID
}
messageRow, err := r.queries.GetAttachmentsForMessages(dbCtx, messageIDs)
if err != nil {
return nil, convertDBError(err)
}
mapMessagesAtt := make(map[string][]string)
for index, _ := range messageRow {
messageID := messageRow[index].MessageID.String()
attachmentID := messageRow[index].AttachmentID.String()
mapMessagesAtt[messageID] = append(mapMessagesAtt[messageID], attachmentID)
}
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,
AttachmentIDs: mapMessagesAtt[sqlcMessage.ID.String()],
CreatedAt: sqlcMessage.CreatedAt.Time}
}
return messages, nil
}
+85
View File
@@ -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
}
+17
View File
@@ -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
}
+38
View File
@@ -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)
}
+127
View File
@@ -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
}
+13
View File
@@ -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)
}
+12
View File
@@ -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)
}
+143
View File
@@ -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
}
+204
View File
@@ -0,0 +1,204 @@
package service
import (
"context"
"crypto/sha256"
"encoding/hex"
"highload/internal/model"
"highload/internal/repository"
"highload/internal/storage"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"strings"
"unicode/utf8"
"github.com/google/uuid"
)
const MaxAttachmentBytes = 10 * 1024 * 1024
const maxImagePixels = 40_000_000
const attachmentObjectPrefix = "attachments/"
type AttachmentService struct {
repo repository.AttachmentRepository
chatService *ChatService
objects storage.ObjectWriter
}
func NewAttachmentService(repo repository.AttachmentRepository, chatService *ChatService, objects storage.ObjectWriter) *AttachmentService {
return &AttachmentService{repo: repo, chatService: chatService, objects: objects}
}
func (s *AttachmentService) CreateAttachment(ctx context.Context, chatID, userID, filename, declaredContentType string, body io.ReadSeeker, size int64) (*model.Attachment, error) {
chat, err := s.chatService.GetChatByID(ctx, chatID, userID)
if err != nil {
return nil, err
}
mimeType, err := validateAttachment(filename, declaredContentType, body, size)
if err != nil {
return nil, err
}
key := attachmentObjectPrefix + uuid.NewString()
if err := ctx.Err(); err != nil {
return nil, err
}
sum := sha256.New()
n, err := io.Copy(sum, io.LimitReader(body, size+1))
if err != nil || n != size {
return nil, ErrServerError
}
if _, err := body.Seek(0, io.SeekStart); err != nil {
return nil, ErrServerError
}
sumString := hex.EncodeToString(sum.Sum(nil))
var attachment *model.Attachment
fn := func(ctx context.Context, tx repository.AttachmentTx) error {
err := s.objects.Put(ctx, key, mimeType, body, size)
if err != nil {
return convertStorageError(err)
}
params := repository.CreateAttachmentParams{
ChatID: chat.ID,
OwnerID: userID,
Filename: filename,
ObjectKey: key,
ContentType: mimeType,
Sha256: sumString,
SizeBytes: size,
}
attachment, err = tx.CreateAttachment(ctx, params)
if err != nil {
return err
}
return nil
}
acquired, err := s.repo.WithObjectKeyLock(ctx, key, fn)
if err != nil {
return nil, convertRepoError(err)
}
if !acquired {
return nil, ErrServiceUnavailable
}
return attachment, nil
}
func (s *AttachmentService) GetAttachment(ctx context.Context, userID, attachmentID string) (*model.Attachment, error) {
_, err := uuid.Parse(attachmentID)
if err != nil {
return nil, ErrInvalidInput
}
_, err = uuid.Parse(userID)
if err != nil {
return nil, ErrInvalidInput
}
attachment, err := s.repo.GetAttachmentForUser(ctx, userID, attachmentID)
if err != nil {
return nil, convertRepoError(err)
}
return attachment, nil
}
func (s *AttachmentService) GetAttachmentContent(ctx context.Context, userID, attachmentID string) (*model.Attachment, io.ReadCloser, error) {
attachment, err := s.GetAttachment(ctx, userID, attachmentID)
if err != nil {
return nil, nil, err
}
contentReader, err := s.objects.Get(ctx, attachment.ObjectKey)
if err != nil {
return nil, nil, convertStorageError(err)
}
return attachment, contentReader, nil
}
func validateAttachment(filename, declaredContentType string, body io.ReadSeeker, size int64) (string, error) {
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || utf8.RuneCountInString(filename) > 255 {
return "", ErrInvalidInput
}
if strings.ContainsAny(filename, "/\\") || containsControlChars(filename) {
return "", ErrInvalidInput
}
if size > MaxAttachmentBytes {
return "", ErrPayloadTooLarge
}
if size <= 0 {
return "", ErrUnsupportMediaType
}
if _, err := body.Seek(0, io.SeekStart); err != nil {
return "", ErrServerError
}
imageConfig, format, err := image.DecodeConfig(io.LimitReader(body, size))
if err != nil {
return "", ErrUnsupportMediaType
}
if imageConfig.Height <= 0 || imageConfig.Width <= 0 {
return "", ErrUnsupportMediaType
}
if imageConfig.Width > maxImagePixels/imageConfig.Height {
return "", ErrPayloadTooLarge
}
var mimeType string
switch format {
case "png":
mimeType = "image/png"
case "jpeg":
mimeType = "image/jpeg"
default:
return "", ErrUnsupportMediaType
}
if mimeType != declaredContentType {
return "", ErrUnsupportMediaType
}
if _, err := body.Seek(0, io.SeekStart); err != nil {
return "", ErrServerError
}
_, _, err = image.Decode(io.LimitReader(body, size))
if err != nil {
return "", ErrUnsupportMediaType
}
if _, err := body.Seek(0, io.SeekStart); err != nil {
return "", ErrServerError
}
return mimeType, nil
}
func containsControlChars(s string) bool {
for _, r := range s {
if (r >= 0 && r <= 31) || r == 127 {
return true
}
}
return false
}
+98
View File
@@ -0,0 +1,98 @@
package service
import (
"context"
"highload/internal/repository"
"highload/internal/storage"
"strings"
"time"
)
type AttachmentCleanupOptions struct {
GracePeriod time.Duration
DryRun bool
ListTimeout time.Duration
}
type AttachmentCleanupService struct {
repo repository.AttachmentRepository
objects storage.ObjectCleanup
options *AttachmentCleanupOptions
}
type OrphanReport struct {
Pages int `json:"s3_pages"`
Objects int `json:"objects_scanned"`
Checked int `json:"checked_in_db"`
Busy int `json:"busy"`
Candidates int `json:"orphan_candidates"`
Deleted int `json:"objects_deleted"`
}
func NewAttachmentCleanupService(repo repository.AttachmentRepository, objects storage.ObjectCleanup, options *AttachmentCleanupOptions) *AttachmentCleanupService {
return &AttachmentCleanupService{repo: repo, objects: objects, options: options}
}
func (s *AttachmentCleanupService) RunOnce(ctx context.Context) error {
_, err := s.ScanOrphans(ctx)
return err
}
func (s *AttachmentCleanupService) ScanOrphans(ctx context.Context) (OrphanReport, error) {
var report OrphanReport
cutoff := time.Now().Add(-s.options.GracePeriod)
var token *string
for {
if err := ctx.Err(); err != nil {
return report, err
}
listCtx, cancel := context.WithTimeout(ctx, s.options.ListTimeout)
objects, nextToken, err := s.objects.ListPage(listCtx, token, attachmentObjectPrefix)
cancel()
if err != nil {
return report, err
}
report.Pages++
for _, obj := range objects {
report.Objects++
if !strings.HasPrefix(obj.Key, attachmentObjectPrefix) ||
obj.LastModified.IsZero() || !obj.LastModified.Before(cutoff) {
continue
}
acquired, err := s.repo.WithObjectKeyLock(ctx, obj.Key, func(txCtx context.Context, txRepo repository.AttachmentTx) error {
exists, err := txRepo.ExistsByObjectKey(txCtx, obj.Key)
if err != nil {
return err
}
report.Checked++
if exists {
return nil
}
report.Candidates++
if s.options.DryRun {
return nil
}
if err := s.objects.Delete(txCtx, obj.Key); err != nil {
return err
}
report.Deleted++
return nil
})
if err != nil {
return report, err
}
if !acquired {
report.Busy++
}
}
if nextToken == nil {
return report, ctx.Err()
}
token = nextToken
}
}
+162
View File
@@ -0,0 +1,162 @@
package service
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"highload/internal/repository"
"highload/internal/storage"
"io"
"strings"
"time"
)
const attachmentReconcilePageSize = 200
const missingSampleLimit = 32
type attachmentReconcileStorage interface {
Check(context.Context) error
Head(context.Context, string) error
PutIfAbsent(context.Context, string, string, io.ReadSeeker, int64) error
}
type AttachmentReconciler struct {
repo repository.AttachmentReconcileRepository
objects attachmentReconcileStorage
options AttachmentCleanupOptions
}
type MissingReport struct {
Pages int `json:"db_pages"`
Rows int `json:"rows_scanned"`
Heads int `json:"s3_head_attempts"`
Missing int `json:"missing_objects"`
SampleIDs []string `json:"missing_attachment_ids"`
}
func NewAttachmentReconciler(repo repository.AttachmentReconcileRepository, objects attachmentReconcileStorage, options AttachmentCleanupOptions) *AttachmentReconciler {
return &AttachmentReconciler{repo: repo, objects: objects, options: options}
}
// ScanMissing checks old committed attachment rows using S3 metadata requests.
func (s *AttachmentReconciler) ScanMissing(ctx context.Context) (MissingReport, error) {
report := MissingReport{SampleIDs: []string{}}
cutoff := time.Now().Add(-s.options.GracePeriod)
if err := s.checkBucket(ctx); err != nil {
return report, err
}
var afterKey string
for {
rows, err := s.repo.ListAttachmentKeys(ctx, afterKey, attachmentReconcilePageSize)
if err != nil {
return report, err
}
report.Pages++
for _, row := range rows {
report.Rows++
if !strings.HasPrefix(row.ObjectKey, attachmentObjectPrefix) ||
row.CreatedAt.IsZero() || !row.CreatedAt.Before(cutoff) {
continue
}
report.Heads++
present, err := s.objectPresent(ctx, row.ObjectKey)
if err != nil {
return report, err
}
if !present {
report.Missing++
if len(report.SampleIDs) < missingSampleLimit {
report.SampleIDs = append(report.SampleIDs, row.ID)
}
}
}
if len(rows) < attachmentReconcilePageSize {
return report, ctx.Err()
}
afterKey = rows[len(rows)-1].ObjectKey
}
}
// Restore verifies the original bytes before writing a missing object under its existing key.
func (s *AttachmentReconciler) Restore(ctx context.Context, id string, original io.Reader) (string, error) {
attachment, err := s.repo.GetAttachmentByID(ctx, id)
if err != nil {
return "", err
}
if !strings.HasPrefix(attachment.ObjectKey, attachmentObjectPrefix) ||
attachment.CreatedAt.IsZero() || !attachment.CreatedAt.Before(time.Now().Add(-s.options.GracePeriod)) {
return "", errors.New("attachment is outside the restore scope or still within grace")
}
if attachment.SizeBytes <= 0 || attachment.SizeBytes > MaxAttachmentBytes {
return "", errors.New("invalid original size in attachment metadata")
}
if err := s.checkBucket(ctx); err != nil {
return "", err
}
// Read at most one original. Keep the verified bytes stable until Put completes.
data, err := io.ReadAll(io.LimitReader(original, attachment.SizeBytes+1))
if err != nil {
return "", fmt.Errorf("read backup original: %w", err)
}
sum := sha256.Sum256(data)
if int64(len(data)) != attachment.SizeBytes || hex.EncodeToString(sum[:]) != attachment.SHA256 {
return "", errors.New("backup original does not match the stored size and SHA-256")
}
var result string
acquired, err := s.repo.WithObjectKeyLock(ctx, attachment.ObjectKey, func(txCtx context.Context, txRepo repository.AttachmentTx) error {
current, err := txRepo.GetAttachmentByID(txCtx, id)
if err != nil {
return err
}
if current.ObjectKey != attachment.ObjectKey || current.SizeBytes != attachment.SizeBytes ||
current.SHA256 != attachment.SHA256 || current.ContentType != attachment.ContentType ||
!current.CreatedAt.Equal(attachment.CreatedAt) {
return errors.New("attachment metadata changed during restore")
}
present, err := s.objectPresent(txCtx, current.ObjectKey)
if err != nil {
return err
}
if present {
result = "already_present"
return nil
}
if s.options.DryRun {
result = "would_restore"
return nil
}
if err := s.objects.PutIfAbsent(txCtx, current.ObjectKey, current.ContentType, bytes.NewReader(data), current.SizeBytes); err != nil {
return err
}
result = "restored"
return nil
})
if err != nil {
return "", err
}
if !acquired {
return "", errors.New("attachment key is busy; retry the restore")
}
return result, nil
}
func (s *AttachmentReconciler) checkBucket(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, s.options.ListTimeout)
defer cancel()
return s.objects.Check(ctx)
}
func (s *AttachmentReconciler) objectPresent(ctx context.Context, key string) (bool, error) {
headCtx, cancel := context.WithTimeout(ctx, s.options.ListTimeout)
defer cancel()
err := s.objects.Head(headCtx, key)
if errors.Is(err, storage.ErrObjectNotFound) {
return false, nil
}
return err == nil, err
}
+142
View File
@@ -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
}
+194
View File
@@ -0,0 +1,194 @@
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
}
_, err = uuid.Parse(userID)
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"`
}
+63
View File
@@ -0,0 +1,63 @@
package service
import (
"errors"
"fmt"
"highload/internal/repository"
"highload/internal/storage"
)
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")
ErrUnsupportMediaType = errors.New("unsupported mediaType")
ErrPayloadTooLarge = errors.New("payload too large")
)
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) || errors.Is(err, repository.ErrServerError):
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)
}
func convertStorageError(err error) error {
var category error
switch {
case errors.Is(err, storage.ErrObjectNotFound):
category = ErrNotFound
case errors.Is(err, storage.ErrServiceUnavailable):
category = ErrServiceUnavailable
case errors.Is(err, storage.ErrStorage):
category = ErrServerError
default:
return err
}
return fmt.Errorf("%w: %v", category, err)
}
+63
View File
@@ -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
}
+142
View File
@@ -0,0 +1,142 @@
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, attachmentIDs []string) (*model.Message, error) {
_, err := s.chatService.GetChatByID(ctx, chatID, userID)
if err != nil {
return nil, err
}
lenText := utf8.RuneCountInString(text)
if lenText > 4000 || (strings.TrimSpace(text) == "" && len(attachmentIDs) == 0) {
return nil, ErrInvalidInput
}
if len(attachmentIDs) > 10 {
return nil, ErrInvalidInput
}
seen := make(map[uuid.UUID]struct{}, len(attachmentIDs))
for _, rawID := range attachmentIDs {
id, err := uuid.Parse(rawID)
if err != nil {
return nil, ErrInvalidInput
}
if _, exists := seen[id]; exists {
return nil, ErrInvalidInput
}
seen[id] = struct{}{}
}
message, err := s.repo.CreateMessage(ctx, chatID, userID, text, key, attachmentIDs)
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"`
}
+70
View File
@@ -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
}
+9
View File
@@ -0,0 +1,9 @@
package storage
import "errors"
var (
ErrServiceUnavailable = errors.New("object storage unavailable")
ErrStorage = errors.New("storage error")
ErrObjectNotFound = errors.New("object not found")
)
@@ -0,0 +1,16 @@
package storage
import (
"context"
"time"
)
type ObjectCleanup interface {
ListPage(ctx context.Context, token *string, prefix string) ([]ObjectInfo, *string, error)
Delete(ctx context.Context, key string) error
}
type ObjectInfo struct {
Key string
LastModified time.Time
}
+11
View File
@@ -0,0 +1,11 @@
package storage
import (
"context"
"io"
)
type ObjectWriter interface {
Put(ctx context.Context, key, contentType string, body io.ReadSeeker, size int64) error
Get(ctx context.Context, key string) (io.ReadCloser, error)
}
+160
View File
@@ -0,0 +1,160 @@
package s3
import (
"context"
"fmt"
"highload/internal/config"
"highload/internal/storage"
"io"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
)
type Storage struct {
Client *awss3.Client
Bucket string
}
func NewStorage(ctx context.Context, cfg *config.S3) (*Storage, error) {
provider := credentials.NewStaticCredentialsProvider(
cfg.AccessKeyID,
cfg.SecretAccessKey,
"",
)
sdkConfig, err := awsconfig.LoadDefaultConfig(
ctx,
awsconfig.WithRegion(cfg.Region),
awsconfig.WithCredentialsProvider(provider),
)
if err != nil {
return nil, err
}
client := awss3.NewFromConfig(sdkConfig, func(opts *awss3.Options) {
opts.BaseEndpoint = aws.String(cfg.Endpoint)
opts.UsePathStyle = true
})
return &Storage{
Client: client,
Bucket: cfg.Bucket,
}, nil
}
func (s *Storage) Check(ctx context.Context) error {
_, err := s.Client.HeadBucket(ctx, &awss3.HeadBucketInput{
Bucket: aws.String(s.Bucket),
})
if err != nil {
return convertS3Error(err)
}
return nil
}
func (s *Storage) Head(ctx context.Context, key string) error {
_, err := s.Client.HeadObject(ctx, &awss3.HeadObjectInput{
Bucket: &s.Bucket,
Key: &key,
})
if err != nil {
return convertS3Error(err)
}
return nil
}
func (s *Storage) Put(ctx context.Context, key, contentType string, body io.ReadSeeker, size int64) error {
return s.put(ctx, key, contentType, body, size, nil)
}
func (s *Storage) PutIfAbsent(ctx context.Context, key, contentType string, body io.ReadSeeker, size int64) error {
return s.put(ctx, key, contentType, body, size, aws.String("*"))
}
func (s *Storage) put(ctx context.Context, key, contentType string, body io.ReadSeeker, size int64, ifNoneMatch *string) error {
_, err := s.Client.PutObject(ctx, &awss3.PutObjectInput{
Bucket: &s.Bucket,
Key: &key,
Body: body,
ContentLength: aws.Int64(size),
IfNoneMatch: ifNoneMatch,
ContentType: &contentType})
if err != nil {
return convertS3Error(err)
}
return nil
}
func (s *Storage) Get(ctx context.Context, key string) (io.ReadCloser, error) {
params := &awss3.GetObjectInput{
Bucket: &s.Bucket,
Key: &key,
}
objectOutput, err := s.Client.GetObject(ctx, params)
if err != nil {
return nil, convertS3Error(err)
}
return objectOutput.Body, nil
}
func (s *Storage) Delete(ctx context.Context, key string) error {
params := &awss3.DeleteObjectInput{
Bucket: &s.Bucket,
Key: &key,
}
_, err := s.Client.DeleteObject(ctx, params)
if err != nil {
return convertS3Error(err)
}
return nil
}
func (s *Storage) ListPage(ctx context.Context, token *string, prefix string) ([]storage.ObjectInfo, *string, error) {
input := awss3.ListObjectsV2Input{
Bucket: &s.Bucket,
Prefix: aws.String(prefix),
ContinuationToken: token,
}
output, err := s.Client.ListObjectsV2(ctx, &input)
if err != nil {
return nil, nil, convertS3Error(err)
}
var objects []storage.ObjectInfo
for _, obj := range output.Contents {
if obj.Key == nil || obj.LastModified == nil || *obj.Key == "" {
continue
}
objects = append(objects, storage.ObjectInfo{
Key: *obj.Key,
LastModified: *obj.LastModified,
})
}
if !aws.ToBool(output.IsTruncated) {
return objects, nil, nil
}
nextToken := output.NextContinuationToken
if nextToken == nil || aws.ToString(nextToken) == "" || aws.ToString(nextToken) == aws.ToString(token) {
return nil, nil, fmt.Errorf("%w: invalid next token", storage.ErrStorage)
}
return objects, nextToken, nil
}
+35
View File
@@ -0,0 +1,35 @@
package s3
import (
"context"
"errors"
"fmt"
"highload/internal/storage"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
func convertS3Error(err error) error {
category := storage.ErrStorage
var sendErr *smithyhttp.RequestSendError
var responseErr *smithyhttp.ResponseError
switch {
case errors.Is(err, context.Canceled):
//Ошибка storage.ErrStorage
case errors.Is(err, context.DeadlineExceeded) || errors.As(err, &sendErr):
category = storage.ErrServiceUnavailable
case errors.As(err, &responseErr):
code := responseErr.HTTPStatusCode()
switch code {
case 404:
category = storage.ErrObjectNotFound
case 429, 500, 503, 504, 502:
category = storage.ErrServiceUnavailable
}
}
return fmt.Errorf("%w: %v", category, err)
}
@@ -0,0 +1,168 @@
package handler
import (
"errors"
"highload/internal/service"
"highload/internal/transport/http/httputils"
"highload/internal/transport/http/middleware"
"io"
"log/slog"
"net/http"
"os"
"time"
)
type AttachmentHandler struct {
attachmentService *service.AttachmentService
uploadSlots chan struct{}
}
func NewAttachmentHandler(attachmentService *service.AttachmentService) *AttachmentHandler {
uploadSlots := make(chan struct{}, 1)
return &AttachmentHandler{attachmentService: attachmentService, uploadSlots: uploadSlots}
}
func (h *AttachmentHandler) CreateAttachment(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
chatID := r.PathValue("chat_id")
filename := r.URL.Query().Get("filename")
contentType := r.Header.Get("Content-Type")
select {
case h.uploadSlots <- struct{}{}:
defer func() { <-h.uploadSlots }()
case <-time.After(1 * time.Second):
w.Header().Set("Retry-After", "1")
httputils.WriteError(w, http.StatusTooManyRequests, httputils.ErrorDetails{
Code: "rate_limited",
Message: "too many concurrent uploads, try again later",
RequestID: requestID,
})
return
case <-r.Context().Done():
return
}
file, err := os.CreateTemp("", "attachment-*")
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
defer file.Close()
if err := os.Remove(file.Name()); err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
body := http.MaxBytesReader(w, r.Body, service.MaxAttachmentBytes)
defer body.Close()
size, err := io.Copy(file, uploadBodyReader{body})
var maxErr *http.MaxBytesError
if errors.As(err, &maxErr) {
httputils.WriteError(w, http.StatusRequestEntityTooLarge, httputils.ErrorDetails{
Code: "payload_too_large",
Message: "payload_too_large",
RequestID: requestID,
})
return
}
if err != nil {
var readErr *uploadBodyReadError
if !errors.As(err, &readErr) {
httputils.WriteServiceError(w, err, requestID)
return
}
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
Code: "invalid_request",
Message: "invalid_request",
RequestID: requestID,
})
return
}
attachment, err := h.attachmentService.CreateAttachment(r.Context(), chatID, userID, filename, contentType, file, size)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
response := convertAttachmentModelToResponse(attachment)
wrErr := httputils.WriteJSON[attachmentResponse](w, http.StatusCreated, *response)
if wrErr != nil {
slog.Error("failed to write create attachment response", "error", wrErr, "requestID", requestID)
}
}
type uploadBodyReader struct{ io.Reader }
func (r uploadBodyReader) Read(p []byte) (int, error) {
n, err := r.Reader.Read(p)
if err != nil && err != io.EOF {
return n, &uploadBodyReadError{err}
}
return n, err
}
type uploadBodyReadError struct{ cause error }
func (e *uploadBodyReadError) Error() string { return e.cause.Error() }
func (e *uploadBodyReadError) Unwrap() error { return e.cause }
func (h *AttachmentHandler) GetAttachment(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
attachmentID := r.PathValue("attachment_id")
attachment, err := h.attachmentService.GetAttachment(r.Context(), userID, attachmentID)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
wrErr := httputils.WriteJSON[attachmentResponse](w, http.StatusOK, *convertAttachmentModelToResponse(attachment))
if wrErr != nil {
slog.Error("failed to write get attachment response", "error", wrErr, "requestID", requestID)
}
}
func (h *AttachmentHandler) GetAttachmentContent(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
attachmentID := r.PathValue("attachment_id")
variant := r.URL.Query().Get("variant")
if variant != "" && variant != "original" {
httputils.WriteError(w, http.StatusNotFound, httputils.ErrorDetails{
Code: "not_found",
Message: "requested variant does not exist",
RequestID: requestID,
})
return
}
attachment, stream, err := h.attachmentService.GetAttachmentContent(r.Context(), userID, attachmentID)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
defer stream.Close()
w.Header().Set("Content-Type", attachment.ContentType)
_, err = io.Copy(w, stream)
if err != nil {
slog.Error("failed to copy attachment content to w", "error", err, "request_id", requestID)
}
}
@@ -0,0 +1,38 @@
package handler
import (
"highload/internal/model"
"highload/internal/transport/http/httputils"
)
type attachmentResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []string `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
func convertAttachmentModelToResponse(attachment *model.Attachment) *attachmentResponse {
return &attachmentResponse{
ID: attachment.ID,
ChatID: attachment.ChatID,
OwnerID: attachment.OwnerID,
Filename: attachment.Filename,
ContentType: attachment.ContentType,
SizeBytes: attachment.SizeBytes,
SHA256: attachment.SHA256,
Status: "ready",
Variants: []string{},
ErrorCode: nil,
CreatedAt: httputils.FormatTime(attachment.CreatedAt),
UpdatedAt: httputils.FormatTime(attachment.UpdatedAt),
}
}
+94
View File
@@ -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"`
}
+102
View File
@@ -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),
}
}
+86
View File
@@ -0,0 +1,86 @@
package handler
import (
"context"
"highload/internal/storage/s3"
"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
s3Storage *s3.Storage
}
func NewHealthHandler(pool *pgxpool.Pool, redisClient *redis.Client, s3Storage *s3.Storage) *HealthHandler {
return &HealthHandler{pool: pool, redisClient: redisClient, s3Storage: s3Storage}
}
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.WriteServiceUnavailable(w, 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.WriteServiceUnavailable(w, requestID); writeErr != nil {
slog.Error("failed to write readiness response", "error", writeErr)
}
return
}
if err := h.s3Storage.Check(ctx); err != nil {
slog.Error("s3 storage check failed", "error", err)
if writeErr := httputils.WriteServiceUnavailable(w, 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, req.AttachmentIDs)
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,42 @@
package handler
import (
"highload/internal/model"
"highload/internal/transport/http/httputils"
)
type messageCreateRequest struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
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"`
AttachmentIDs []string `json:"attachment_ids"`
}
type messageGetResponse struct {
Items []messageResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func convertMessageModelToResponse(message *model.Message) *messageResponse {
attachmentIDs := message.AttachmentIDs
if attachmentIDs == nil {
attachmentIDs = []string{}
}
return &messageResponse{
ID: message.ID,
ChatID: message.ChatID,
SenderID: message.SenderID,
Text: message.Text,
AttachmentIDs: attachmentIDs,
CreatedAt: httputils.FormatTime(message.CreatedAt),
}
}
+60
View File
@@ -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),
}
}
+207
View File
@@ -0,0 +1,207 @@
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"
case errors.Is(err, service.ErrPayloadTooLarge):
return http.StatusRequestEntityTooLarge, "payload_too_large"
case errors.Is(err, service.ErrUnsupportMediaType):
return http.StatusUnsupportedMediaType, "unsupported_media_type"
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 WriteServiceUnavailable(w http.ResponseWriter, requestID string) error {
return WriteError(
w,
http.StatusServiceUnavailable,
ErrorDetails{
Message: "unavailable",
Code: "unavailable",
RequestID: requestID,
},
)
}
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()),
)
})
}
+57
View File
@@ -0,0 +1,57 @@
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
attachmentHandler *handler.AttachmentHandler
}
func NewRouter(middleware *middleware.Middleware, authHandler *handler.AuthHandler, healthHandler *handler.HealthHandler, chatHandler *handler.ChatHandler, userHandler *handler.UserHandler, messageHandler *handler.MessageHandler, attachmentHandler *handler.AttachmentHandler) *Router {
return &Router{chatHandler: chatHandler, authHandler: authHandler, healthHandler: healthHandler, middleware: middleware, userHandler: userHandler, messageHandler: messageHandler, attachmentHandler: attachmentHandler}
}
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)
//Attachment
protectedMux.HandleFunc("POST /api/v1/chats/{chat_id}/attachments", r.attachmentHandler.CreateAttachment)
protectedMux.HandleFunc("GET /api/v1/attachments/{attachment_id}", r.attachmentHandler.GetAttachment)
protectedMux.HandleFunc("GET /api/v1/attachments/{attachment_id}/content", r.attachmentHandler.GetAttachmentContent)
mux.Handle("/api/v1/", r.middleware.Auth(protectedMux))
return r.middleware.InstanceID(r.middleware.RequestID(
r.middleware.Logging(mux),
))
}