import lab3 files
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
DatabaseURL string
|
||||
SessionStore string
|
||||
CacheURL string
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
ShutdownDrain time.Duration
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
dsn, err := readSecret("DATABASE_URL_FILE", "DATABASE_URL")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("database url: %w", err)
|
||||
}
|
||||
|
||||
cacheURL, err := readSecretOptional("CACHE_URL_FILE", "CACHE_URL")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cache url: %w", err)
|
||||
}
|
||||
|
||||
ttlSeconds, err := readInt("SESSION_TTL_SECONDS", 3600)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SESSION_TTL_SECONDS: %w", err)
|
||||
}
|
||||
if ttlSeconds <= 0 {
|
||||
return nil, fmt.Errorf("SESSION_TTL_SECONDS должен быть положительным")
|
||||
}
|
||||
|
||||
idemSeconds, err := readInt("IDEMPOTENCY_TTL_SECONDS", 86400)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS: %w", err)
|
||||
}
|
||||
if idemSeconds <= 0 {
|
||||
return nil, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS должен быть положительным")
|
||||
}
|
||||
|
||||
drainSeconds, err := readInt("SHUTDOWN_DRAIN_SECONDS", 3)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS: %w", err)
|
||||
}
|
||||
if drainSeconds < 0 {
|
||||
return nil, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS не может быть отрицательным")
|
||||
}
|
||||
|
||||
store := strings.ToLower(getenv("SESSION_STORE", "postgres"))
|
||||
switch store {
|
||||
case "postgres", "redis", "valkey":
|
||||
default:
|
||||
return nil, fmt.Errorf("SESSION_STORE=%q не поддерживается", store)
|
||||
}
|
||||
|
||||
return &Config{
|
||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||
Port: getenv("APP_PORT", "8080"),
|
||||
DatabaseURL: dsn,
|
||||
SessionStore: store,
|
||||
CacheURL: cacheURL,
|
||||
SessionTTL: time.Duration(ttlSeconds) * time.Second,
|
||||
IdempotencyTTL: time.Duration(idemSeconds) * time.Second,
|
||||
ShutdownDrain: time.Duration(drainSeconds) * time.Second,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func getenv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func readInt(key string, def int) (int, error) {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def, nil
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("не целое число: %q", v)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func readSecret(fileEnv, envKey string) (string, error) {
|
||||
v, err := readSecretOptional(fileEnv, envKey)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if v == "" {
|
||||
return "", fmt.Errorf("не задан %s или %s", fileEnv, envKey)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func readSecretOptional(fileEnv, envKey string) (string, error) {
|
||||
if path := os.Getenv(fileEnv); path != "" {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("чтение %s=%s: %w", fileEnv, path, err)
|
||||
}
|
||||
s := strings.TrimSpace(string(b))
|
||||
if s == "" {
|
||||
return "", fmt.Errorf("файл %s пуст", path)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
return os.Getenv(envKey), nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Health struct {
|
||||
Status string
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID string
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string // в DTO UserResponse его не будет
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string
|
||||
ChatID string
|
||||
SenderID string
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
TokenHash []byte
|
||||
UserID string
|
||||
ExpiresAt time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type ErrorCode string
|
||||
|
||||
const (
|
||||
CodeInvalidRequest ErrorCode = "invalid_request"
|
||||
CodeUnauthorized ErrorCode = "unauthorized"
|
||||
CodeNotFound ErrorCode = "not_found"
|
||||
CodeConflict ErrorCode = "conflict"
|
||||
CodeUnsupportedMediaType ErrorCode = "unsupported_media_type"
|
||||
CodeInternalError ErrorCode = "internal_error"
|
||||
CodeUnavailable ErrorCode = "unavailable"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("не найдено")
|
||||
ErrAlreadyExists = errors.New("уже существует")
|
||||
ErrInvalidInput = errors.New("некорректные данные")
|
||||
ErrUnauthorized = errors.New("требуется аутентификация")
|
||||
ErrUnsupportedMediaType = errors.New("неподдерживаемый тип содержимого")
|
||||
ErrUnavailable = errors.New("сервис недоступен")
|
||||
)
|
||||
|
||||
type NotFoundError struct {
|
||||
Entity string
|
||||
ID string
|
||||
}
|
||||
|
||||
func (e *NotFoundError) Error() string {
|
||||
return fmt.Sprintf("%s с id %q не найден", e.Entity, e.ID)
|
||||
}
|
||||
func (e *NotFoundError) Unwrap() error { return ErrNotFound }
|
||||
func (e *NotFoundError) Code() ErrorCode { return CodeNotFound }
|
||||
|
||||
type AlreadyExistsError struct {
|
||||
Entity string
|
||||
Field string
|
||||
Value string
|
||||
}
|
||||
|
||||
func (e *AlreadyExistsError) Error() string {
|
||||
return fmt.Sprintf("%s с %s %q уже существует", e.Entity, e.Field, e.Value)
|
||||
}
|
||||
func (e *AlreadyExistsError) Unwrap() error { return ErrAlreadyExists }
|
||||
func (e *AlreadyExistsError) Code() ErrorCode { return CodeConflict }
|
||||
|
||||
type IdempotencyConflictError struct {
|
||||
Key string
|
||||
}
|
||||
|
||||
func (e *IdempotencyConflictError) Error() string {
|
||||
return "Idempotency-Key " + e.Key + " уже использован с другим телом запроса"
|
||||
}
|
||||
|
||||
func (e *IdempotencyConflictError) Unwrap() error { return ErrAlreadyExists }
|
||||
func (e *IdempotencyConflictError) Code() ErrorCode { return CodeConflict }
|
||||
|
||||
type ValidationError struct {
|
||||
Field string
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *ValidationError) Error() string {
|
||||
return fmt.Sprintf("ошибка валидации поля %q: %s", e.Field, e.Message)
|
||||
}
|
||||
func (e *ValidationError) Unwrap() error { return ErrInvalidInput }
|
||||
func (e *ValidationError) Code() ErrorCode { return CodeInvalidRequest }
|
||||
|
||||
type UnauthorizedError struct {
|
||||
Reason string // для логов; в JSON не попадает
|
||||
}
|
||||
|
||||
func (e *UnauthorizedError) Error() string {
|
||||
return "требуется аутентификация"
|
||||
}
|
||||
func (e *UnauthorizedError) Unwrap() error { return ErrUnauthorized }
|
||||
func (e *UnauthorizedError) Code() ErrorCode { return CodeUnauthorized }
|
||||
|
||||
type UnsupportedMediaTypeError struct {
|
||||
MediaType string
|
||||
}
|
||||
|
||||
func (e *UnsupportedMediaTypeError) Error() string {
|
||||
if e.MediaType == "" {
|
||||
return "требуется Content-Type: application/json"
|
||||
}
|
||||
return fmt.Sprintf("неподдерживаемый Content-Type %q; требуется application/json", e.MediaType)
|
||||
}
|
||||
func (e *UnsupportedMediaTypeError) Unwrap() error { return ErrUnsupportedMediaType }
|
||||
func (e *UnsupportedMediaTypeError) Code() ErrorCode { return CodeUnsupportedMediaType }
|
||||
|
||||
type UnavailableError struct {
|
||||
Reason string // для логов; в JSON не попадает
|
||||
}
|
||||
|
||||
func (e *UnavailableError) Error() string {
|
||||
return "сервис временно недоступен"
|
||||
}
|
||||
func (e *UnavailableError) Unwrap() error { return ErrUnavailable }
|
||||
func (e *UnavailableError) Code() ErrorCode { return CodeUnavailable }
|
||||
@@ -0,0 +1,23 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
)
|
||||
|
||||
type IdempotencyScope struct {
|
||||
UserID string
|
||||
Method string
|
||||
Path string
|
||||
Key string
|
||||
}
|
||||
|
||||
type CreateIdempotentResult struct {
|
||||
Status int
|
||||
Body []byte
|
||||
Replayed bool
|
||||
}
|
||||
|
||||
func RequestHash(text string) []byte {
|
||||
sum := sha256.Sum256([]byte(text))
|
||||
return sum[:]
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type UserRepository interface {
|
||||
Create(ctx context.Context, user *User) error
|
||||
GetByID(ctx context.Context, id string) (*User, error)
|
||||
GetByUsername(ctx context.Context, username string) (*User, error)
|
||||
}
|
||||
|
||||
type ChatRepository interface {
|
||||
Create(ctx context.Context, chat *Chat) error
|
||||
GetByID(ctx context.Context, id string) (*Chat, error)
|
||||
ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]Chat, *string, error)
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
Create(ctx context.Context, message *Message) error
|
||||
ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]Message, *string, error)
|
||||
CreateIdempotent(
|
||||
ctx context.Context,
|
||||
scope IdempotencyScope,
|
||||
requestHash []byte,
|
||||
fresh *Message,
|
||||
freshResponse []byte,
|
||||
ttl time.Duration,
|
||||
) (*CreateIdempotentResult, error)
|
||||
}
|
||||
|
||||
type SessionRepository interface {
|
||||
Create(ctx context.Context, session *Session) error
|
||||
GetByTokenHash(ctx context.Context, tokenHash []byte) (*Session, error)
|
||||
DeleteByTokenHash(ctx context.Context, tokenHash []byte) error
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title" binding:"required,min=1,max=100"`
|
||||
MemberIDs []string `json:"member_ids" binding:"required,min=1,max=100,dive,uuid"`
|
||||
}
|
||||
|
||||
type ChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type ChatPageResponse struct {
|
||||
Items []ChatResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func ChatFromDomain(c *domain.Chat) ChatResponse {
|
||||
return ChatResponse{
|
||||
ID: c.ID,
|
||||
Title: c.Title,
|
||||
MemberIDs: append([]string(nil), c.MemberIDs...),
|
||||
CreatedAt: c.CreatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
|
||||
func ChatsFromDomain(items []domain.Chat) []ChatResponse {
|
||||
out := make([]ChatResponse, len(items))
|
||||
for i := range items {
|
||||
out[i] = ChatFromDomain(&items[i])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
// делаем вложенный ответ через вкладку ErrorBody в обертку.
|
||||
|
||||
type ErrorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error ErrorBody `json:"error"`
|
||||
}
|
||||
|
||||
type coded interface {
|
||||
Code() domain.ErrorCode
|
||||
}
|
||||
|
||||
func ErrorFromDomain(err error, requestID string) ErrorResponse {
|
||||
var c coded
|
||||
if errors.As(err, &c) {
|
||||
code := c.Code()
|
||||
message := err.Error()
|
||||
if code == domain.CodeInternalError {
|
||||
message = "внутренняя ошибка"
|
||||
}
|
||||
return ErrorResponse{Error: ErrorBody{
|
||||
Code: string(code),
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
}}
|
||||
}
|
||||
code := domain.CodeInternalError
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
code = domain.CodeNotFound
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
code = domain.CodeConflict
|
||||
case errors.Is(err, domain.ErrInvalidInput):
|
||||
code = domain.CodeInvalidRequest
|
||||
case errors.Is(err, domain.ErrUnauthorized):
|
||||
code = domain.CodeUnauthorized
|
||||
case errors.Is(err, domain.ErrUnsupportedMediaType):
|
||||
code = domain.CodeUnsupportedMediaType
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
code = domain.CodeUnavailable
|
||||
}
|
||||
message := err.Error()
|
||||
if code == domain.CodeInternalError {
|
||||
message = "внутренняя ошибка"
|
||||
}
|
||||
return ErrorResponse{Error: ErrorBody{
|
||||
Code: string(code),
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
}}
|
||||
}
|
||||
|
||||
func StatusFromError(err error) int {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return 404
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return 409
|
||||
case errors.Is(err, domain.ErrInvalidInput):
|
||||
return 400
|
||||
case errors.Is(err, domain.ErrUnauthorized):
|
||||
return 401
|
||||
case errors.Is(err, domain.ErrUnsupportedMediaType):
|
||||
return 415
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
return 503
|
||||
default:
|
||||
return 500
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package dto
|
||||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text" binding:"required,min=1,max=4000"`
|
||||
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"`
|
||||
}
|
||||
|
||||
type MessagePageResponse struct {
|
||||
Items []MessageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func MessageFromDomain(m *domain.Message) MessageResponse {
|
||||
return MessageResponse{
|
||||
ID: m.ID,
|
||||
ChatID: m.ChatID,
|
||||
SenderID: m.SenderID,
|
||||
Text: m.Text,
|
||||
CreatedAt: m.CreatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
|
||||
func MessagesFromDomain(items []domain.Message) []MessageResponse {
|
||||
out := make([]MessageResponse, len(items))
|
||||
for i := range items {
|
||||
out[i] = MessageFromDomain(&items[i])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
|
||||
func SessionResponseFromDomain(s *domain.Session, token string, u *domain.User) SessionResponse {
|
||||
return SessionResponse{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: s.ExpiresAt.UTC().Format(timeFormat),
|
||||
User: UserFromDomain(u),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
const timeFormat = "2006-01-02T15:04:05.000000Z07:00"
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username" binding:"required,min=3,max=32"`
|
||||
DisplayName string `json:"display_name" binding:"required,min=1,max=100"`
|
||||
Password string `json:"password" binding:"required,min=12,max=512"`
|
||||
}
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func UserFromDomain(u *domain.User) UserResponse {
|
||||
return UserResponse{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
CreatedAt: u.CreatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
sessions *service.SessionService
|
||||
}
|
||||
|
||||
func NewAuthHandler(sessions *service.SessionService) *AuthHandler {
|
||||
return &AuthHandler{sessions: sessions}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(c *gin.Context) {
|
||||
username, password, err := parseBasicAuth(c)
|
||||
if err != nil {
|
||||
respondBasicChallenge(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
session, token, user, err := h.sessions.Login(c.Request.Context(), username, password)
|
||||
if err != nil {
|
||||
respondBasicChallenge(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, dto.SessionResponseFromDomain(session, token, user))
|
||||
}
|
||||
|
||||
// RevokeCurrent отзывает текущую сессию. Токен уже проверен BearerAuth,
|
||||
// поэтому здесь его достаточно передать в SessionService.
|
||||
func (h *AuthHandler) RevokeCurrent(c *gin.Context) {
|
||||
token := middleware.CurrentToken(c)
|
||||
if token == "" {
|
||||
respondError(c, &domain.UnauthorizedError{Reason: "нет токена"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.sessions.Revoke(c.Request.Context(), token); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// parseBasicAuth читает Authorization: Basic base64(username:password).
|
||||
func parseBasicAuth(c *gin.Context) (string, string, error) {
|
||||
const prefix = "Basic "
|
||||
|
||||
auth := c.GetHeader("Authorization")
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "требуется Basic"}
|
||||
}
|
||||
|
||||
decoded, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "некорректный Base64"}
|
||||
}
|
||||
|
||||
username, password, ok := strings.Cut(string(decoded), ":")
|
||||
if !ok || username == "" {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "некорректный Basic-формат"}
|
||||
}
|
||||
|
||||
return username, password, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func bindStrictJSON(c *gin.Context, dst any) error {
|
||||
ct := c.GetHeader("Content-Type")
|
||||
mediaType, _, err := mime.ParseMediaType(ct)
|
||||
if ct == "" || err != nil || !strings.EqualFold(mediaType, "application/json") {
|
||||
return &domain.UnsupportedMediaTypeError{MediaType: ct}
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return &badRequestError{msg: "не удалось прочитать тело запроса"}
|
||||
}
|
||||
_ = c.Request.Body.Close()
|
||||
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return &badRequestError{msg: "тело запроса обязательно"}
|
||||
}
|
||||
return &badRequestError{msg: err.Error()}
|
||||
}
|
||||
|
||||
// Отклоняем любой непустой остаток после первого JSON-значения.
|
||||
var extra json.RawMessage
|
||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return &badRequestError{msg: "тело запроса содержит данные после JSON"}
|
||||
}
|
||||
|
||||
if v := binding.Validator; v != nil {
|
||||
if err := v.ValidateStruct(dst); err != nil {
|
||||
return &badRequestError{msg: err.Error()}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chats *service.ChatService
|
||||
}
|
||||
|
||||
func NewChatHandler(chats *service.ChatService) *ChatHandler {
|
||||
return &ChatHandler{chats: chats}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Create(c *gin.Context) {
|
||||
var req dto.CreateChatRequest
|
||||
if err := bindStrictJSON(c, &req); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chat, err := h.chats.Create(c.Request.Context(), me.ID, req.Title, req.MemberIDs)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.ChatFromDomain(chat))
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Get(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chatID, err := parseUUIDPathParam(c, "chat_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.chats.Get(c.Request.Context(), me.ID, chatID)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.ChatFromDomain(chat))
|
||||
}
|
||||
|
||||
func (h *ChatHandler) List(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
limit, cursor, err := parseListQuery(c)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
items, next, err := h.chats.List(c.Request.Context(), me.ID, limit, cursor)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.ChatPageResponse{
|
||||
Items: dto.ChatsFromDomain(items),
|
||||
NextCursor: next,
|
||||
})
|
||||
}
|
||||
|
||||
func parseListQuery(c *gin.Context) (int, *string, error) {
|
||||
limit := 50
|
||||
if v := c.Query("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, nil, &badRequestError{msg: "limit должен быть целым 1..100"}
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
var cursor *string
|
||||
if v := c.Query("cursor"); v != "" {
|
||||
cursor = &v
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
)
|
||||
|
||||
type HealthCheck func(ctx context.Context) error
|
||||
|
||||
type HealthHandler struct {
|
||||
checks []HealthCheck
|
||||
ready *atomic.Bool
|
||||
}
|
||||
|
||||
func NewHealthHandler(checks ...HealthCheck) *HealthHandler {
|
||||
return &HealthHandler{checks: checks}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) WithReadyFlag(v *atomic.Bool) *HealthHandler {
|
||||
h.ready = v
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Live(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(c *gin.Context) {
|
||||
if h.ready != nil && !h.ready.Load() {
|
||||
respondError(c, &domain.UnavailableError{Reason: "shutting down"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
for _, check := range h.checks {
|
||||
if check == nil {
|
||||
continue
|
||||
}
|
||||
if err := check(ctx); err != nil {
|
||||
respondError(c, &domain.UnavailableError{Reason: "зависимость недоступна"})
|
||||
return
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"})
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type MessageHandler struct {
|
||||
messages *service.MessageService
|
||||
}
|
||||
|
||||
func NewMessageHandler(messages *service.MessageService) *MessageHandler {
|
||||
return &MessageHandler{messages: messages}
|
||||
}
|
||||
|
||||
func (h *MessageHandler) Create(c *gin.Context) {
|
||||
var req dto.CreateMessageRequest
|
||||
if err := bindStrictJSON(c, &req); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
key := c.GetHeader("Idempotency-Key")
|
||||
if key == "" || !idempotencyKeyPattern.MatchString(key) {
|
||||
respondError(c, &badRequestError{
|
||||
msg: "Idempotency-Key обязателен и должен соответствовать ^[A-Za-z0-9._:-]{1,128}$",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chatID, err := parseUUIDPathParam(c, "chat_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.messages.Create(
|
||||
c.Request.Context(),
|
||||
me.ID,
|
||||
chatID,
|
||||
req.Text,
|
||||
key,
|
||||
c.Request.URL.Path,
|
||||
)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Data(result.Status, "application/json", result.Body)
|
||||
}
|
||||
|
||||
func (h *MessageHandler) List(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chatID, err := parseUUIDPathParam(c, "chat_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
limit, cursor, err := parseListQuery(c)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
items, next, err := h.messages.List(c.Request.Context(), me.ID, chatID, limit, cursor)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.MessagePageResponse{
|
||||
Items: dto.MessagesFromDomain(items),
|
||||
NextCursor: next,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
)
|
||||
|
||||
type badRequestError struct{ msg string }
|
||||
|
||||
func (e *badRequestError) Error() string { return e.msg }
|
||||
func (e *badRequestError) Unwrap() error { return domain.ErrInvalidInput }
|
||||
func (e *badRequestError) Code() domain.ErrorCode { return domain.CodeInvalidRequest }
|
||||
|
||||
func parseUUIDPathParam(c *gin.Context, name string) (string, error) {
|
||||
raw := c.Param(name)
|
||||
if raw == "" {
|
||||
return "", &badRequestError{msg: "параметр " + name + " обязателен"}
|
||||
}
|
||||
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
return "", &badRequestError{msg: "параметр " + name + " должен быть корректным UUID"}
|
||||
}
|
||||
|
||||
return id.String(), nil
|
||||
}
|
||||
|
||||
func respondError(c *gin.Context, err error) {
|
||||
reqID := middleware.GetRequestID(c)
|
||||
c.JSON(dto.StatusFromError(err), dto.ErrorFromDomain(err, reqID))
|
||||
}
|
||||
|
||||
// respondBasicChallenge выставляет WWW-Authenticate для 401 на /auth/sessions.
|
||||
// На не-401 ответах заголовок не ставится как по контракту нужно
|
||||
func respondBasicChallenge(c *gin.Context, err error) {
|
||||
if dto.StatusFromError(err) == 401 {
|
||||
c.Header("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
respondError(c, err)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
users *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(users *service.UserService) *UserHandler {
|
||||
return &UserHandler{users: users}
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(c *gin.Context) {
|
||||
var req dto.CreateUserRequest
|
||||
if err := bindStrictJSON(c, &req); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
u, err := h.users.Create(c.Request.Context(), req.Username, req.DisplayName, req.Password)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.UserFromDomain(u))
|
||||
}
|
||||
|
||||
func (h *UserHandler) Current(c *gin.Context) {
|
||||
u := middleware.CurrentUser(c)
|
||||
if u == nil {
|
||||
respondError(c, &badRequestError{msg: "нет текущего пользователя"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.UserFromDomain(u))
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
)
|
||||
|
||||
func Auth(users domain.UserRepository) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.GetHeader("X-User-Id")
|
||||
if id == "" {
|
||||
abortUnauthorized(c, "требуется X-User-Id")
|
||||
return
|
||||
}
|
||||
|
||||
u, err := users.GetByID(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
abortUnauthorized(c, "неизвестный пользователь")
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(CurrentUserKey, u)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func abortUnauthorized(c *gin.Context, msg string) {
|
||||
reqID := GetRequestID(c)
|
||||
body := dto.ErrorFromDomain(
|
||||
&domain.UnauthorizedError{Reason: msg},
|
||||
reqID,
|
||||
)
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, body)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
const authTimeout = 3 * time.Second
|
||||
|
||||
// BearerAuth читает Authorization: Bearer <token>, проверяет сессию
|
||||
// через SessionService и кладёт пользователя и токен в контекст.
|
||||
func BearerAuth(sessions *service.SessionService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token, ok := parseBearerToken(c)
|
||||
if !ok {
|
||||
abortBearer(c, "требуется Bearer")
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), authTimeout)
|
||||
defer cancel()
|
||||
|
||||
user, err := sessions.Resolve(ctx, token)
|
||||
if err != nil {
|
||||
abortBearerWithErr(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(CurrentUserKey, user)
|
||||
c.Set(CurrentTokenKey, token)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// parseBearerToken читает Authorization: Bearer <opaque-token>.
|
||||
func parseBearerToken(c *gin.Context) (string, bool) {
|
||||
const prefix = "Bearer "
|
||||
auth := c.GetHeader("Authorization")
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimSpace(auth[len(prefix):])
|
||||
if token == "" {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func abortBearer(c *gin.Context, reason string) {
|
||||
abortBearerWithErr(c, &domain.UnauthorizedError{Reason: reason})
|
||||
}
|
||||
|
||||
// abortBearerWithErr формирует ответ на ошибку аутентификации.
|
||||
// Заголовок WWW-Authenticate: Bearer выставляется только на 401;
|
||||
// при 503 (недоступность БД/кэша) — обычный ответ ошибки без challenge.
|
||||
func abortBearerWithErr(c *gin.Context, err error) {
|
||||
reqID := GetRequestID(c)
|
||||
status := dto.StatusFromError(err)
|
||||
if status == 401 {
|
||||
c.Header("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
}
|
||||
c.AbortWithStatusJSON(status, dto.ErrorFromDomain(err, reqID))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
CurrentUserKey = "current_user"
|
||||
CurrentTokenKey = "current_token"
|
||||
)
|
||||
|
||||
func CurrentUser(c *gin.Context) *domain.User {
|
||||
if v, ok := c.Get(CurrentUserKey); ok {
|
||||
if u, ok := v.(*domain.User); ok {
|
||||
return u
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func CurrentToken(c *gin.Context) string {
|
||||
if v, ok := c.Get(CurrentTokenKey); ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const InstanceIDHeader = "X-Instance-Id"
|
||||
|
||||
var instanceID = resolveInstanceID()
|
||||
|
||||
func resolveInstanceID() string {
|
||||
if v := os.Getenv("INSTANCE_ID"); v != "" {
|
||||
return v
|
||||
}
|
||||
if v, err := os.Hostname(); err == nil && v != "" {
|
||||
return v
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
|
||||
func Instance() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Set(InstanceIDHeader, instanceID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetInstanceID() string { return instanceID }
|
||||
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
RequestIDKey = "request_id"
|
||||
RequestIDHeader = "X-Request-Id"
|
||||
)
|
||||
|
||||
func RequestID() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.GetHeader(RequestIDHeader)
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
c.Set(RequestIDKey, id)
|
||||
c.Writer.Header().Set(RequestIDHeader, id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetRequestID(c *gin.Context) string {
|
||||
if v, ok := c.Get(RequestIDKey); ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/handler"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
)
|
||||
|
||||
type Handlers struct {
|
||||
Health *handler.HealthHandler
|
||||
User *handler.UserHandler
|
||||
Chat *handler.ChatHandler
|
||||
Message *handler.MessageHandler
|
||||
Auth *handler.AuthHandler
|
||||
}
|
||||
|
||||
func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine {
|
||||
gin.EnableJsonDecoderDisallowUnknownFields()
|
||||
|
||||
r := gin.New()
|
||||
r.Use(gin.Logger())
|
||||
r.Use(gin.Recovery())
|
||||
r.Use(middleware.RequestID())
|
||||
r.Use(middleware.Instance())
|
||||
|
||||
r.GET("/health/live", h.Health.Live)
|
||||
r.GET("/health/ready", h.Health.Ready)
|
||||
|
||||
api := r.Group("/api/v1")
|
||||
{
|
||||
api.POST("/users", h.User.Create)
|
||||
api.POST("/auth/sessions", h.Auth.CreateSession)
|
||||
}
|
||||
|
||||
protected := api.Group("")
|
||||
protected.Use(auth)
|
||||
{
|
||||
protected.DELETE("/auth/sessions/current", h.Auth.RevokeCurrent)
|
||||
|
||||
protected.GET("/users/me", h.User.Current)
|
||||
protected.POST("/chats", h.Chat.Create)
|
||||
protected.GET("/chats", h.Chat.List)
|
||||
protected.GET("/chats/:chat_id", h.Chat.Get)
|
||||
protected.POST("/chats/:chat_id/messages", h.Message.Create)
|
||||
protected.GET("/chats/:chat_id/messages", h.Message.List)
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type ChatService struct {
|
||||
chats domain.ChatRepository
|
||||
users domain.UserRepository
|
||||
}
|
||||
|
||||
func NewChatService(chats domain.ChatRepository, users domain.UserRepository) *ChatService {
|
||||
return &ChatService{chats: chats, users: users}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, creatorID, title string, memberIDs []string) (*domain.Chat, error) {
|
||||
if strings.TrimSpace(title) == "" {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "title",
|
||||
Message: "не может состоять только из пробелов",
|
||||
}
|
||||
}
|
||||
if utf8.RuneCountInString(title) > 100 {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "title",
|
||||
Message: "не более 100 символов",
|
||||
}
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "дубликаты запрещены",
|
||||
}
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
|
||||
if _, ok := seen[creatorID]; !ok {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "создатель должен входить в список участников",
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range memberIDs {
|
||||
if _, err := s.users.GetByID(ctx, id); err != nil {
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "неизвестный участник " + id,
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
c := &domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if err := s.chats.Create(ctx, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(ctx context.Context, userID, chatID string) (*domain.Chat, error) {
|
||||
c, err := s.chats.GetByID(ctx, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, m := range c.MemberIDs {
|
||||
if m == userID {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
return nil, &domain.NotFoundError{Entity: "chat", ID: chatID}
|
||||
}
|
||||
|
||||
func (s *ChatService) List(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) {
|
||||
return s.chats.ListByMember(ctx, userID, limit, cursor)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
)
|
||||
|
||||
type MessageService struct {
|
||||
messages domain.MessageRepository
|
||||
chats domain.ChatRepository
|
||||
idempotencyTTL time.Duration
|
||||
}
|
||||
|
||||
func NewMessageService(
|
||||
messages domain.MessageRepository,
|
||||
chats domain.ChatRepository,
|
||||
idempotencyTTL time.Duration,
|
||||
) *MessageService {
|
||||
return &MessageService{
|
||||
messages: messages,
|
||||
chats: chats,
|
||||
idempotencyTTL: idempotencyTTL,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessageService) Create(ctx context.Context, senderID, chatID, text, idempotencyKey, requestPath string,
|
||||
) (*domain.CreateIdempotentResult, error) {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "text",
|
||||
Message: "не может состоять только из пробелов",
|
||||
}
|
||||
}
|
||||
if utf8.RuneCountInString(text) > 4000 {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "text",
|
||||
Message: "не более 4000 символов",
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.ensureMember(ctx, senderID, chatID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fresh := &domain.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
body, err := json.Marshal(dto.MessageFromDomain(fresh))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.messages.CreateIdempotent(
|
||||
ctx,
|
||||
domain.IdempotencyScope{
|
||||
UserID: senderID,
|
||||
Method: http.MethodPost,
|
||||
Path: requestPath,
|
||||
Key: idempotencyKey,
|
||||
},
|
||||
domain.RequestHash(text),
|
||||
fresh,
|
||||
body,
|
||||
s.idempotencyTTL,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *MessageService) List(ctx context.Context, userID, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
|
||||
if err := s.ensureMember(ctx, userID, chatID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return s.messages.ListByChat(ctx, chatID, limit, cursor)
|
||||
}
|
||||
|
||||
func (s *MessageService) ensureMember(ctx context.Context, userID, chatID string) error {
|
||||
c, err := s.chats.GetByID(ctx, chatID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range c.MemberIDs {
|
||||
if m == userID {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return &domain.NotFoundError{Entity: "chat", ID: chatID}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// PasswordHasher хеширует пароли и проверяет пароль сохранённого хеша.
|
||||
type PasswordHasher interface {
|
||||
Hash(password string) (string, error)
|
||||
Verify(password, encoded string) (bool, error)
|
||||
}
|
||||
|
||||
type Argon2idHasher struct {
|
||||
memory uint32
|
||||
iterations uint32
|
||||
parallelism uint8
|
||||
saltLength uint32
|
||||
keyLength uint32
|
||||
}
|
||||
|
||||
func NewArgon2idHasher() *Argon2idHasher {
|
||||
return &Argon2idHasher{
|
||||
memory: 64 * 1024,
|
||||
iterations: 3,
|
||||
parallelism: 4,
|
||||
saltLength: 16,
|
||||
keyLength: 32,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Argon2idHasher) Hash(password string) (string, error) {
|
||||
salt := make([]byte, h.saltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("генерация соли: %w", err)
|
||||
}
|
||||
|
||||
key := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
h.iterations,
|
||||
h.memory,
|
||||
h.parallelism,
|
||||
h.keyLength,
|
||||
)
|
||||
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
h.memory,
|
||||
h.iterations,
|
||||
h.parallelism,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(key),
|
||||
), nil
|
||||
}
|
||||
|
||||
// Verify сравнивает пароль с сохранённым PHC-хешем.
|
||||
// Возвращает false и nil при неверном пароле.
|
||||
// Возвращает false и ошибку, если строка хеша повреждена или несовместима.
|
||||
func (h *Argon2idHasher) Verify(password, encoded string) (bool, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false, errors.New("некорректный формат хеша")
|
||||
}
|
||||
|
||||
var version int
|
||||
if n, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || n != 1 {
|
||||
return false, errors.New("некорректная версия хеша")
|
||||
}
|
||||
if version != argon2.Version {
|
||||
return false, errors.New("неподдерживаемая версия Argon2")
|
||||
}
|
||||
|
||||
var (
|
||||
memory uint32
|
||||
iterations uint32
|
||||
parallelism uint8
|
||||
)
|
||||
if n, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, ¶llelism); err != nil || n != 3 {
|
||||
return false, errors.New("некорректные параметры хеша")
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, errors.New("некорректная соль")
|
||||
}
|
||||
|
||||
wantKey, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, errors.New("некорректный ключ")
|
||||
}
|
||||
|
||||
gotKey := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
iterations,
|
||||
memory,
|
||||
parallelism,
|
||||
uint32(len(wantKey)),
|
||||
)
|
||||
|
||||
return subtle.ConstantTimeCompare(gotKey, wantKey) == 1, nil
|
||||
}
|
||||
|
||||
var _ PasswordHasher = (*Argon2idHasher)(nil)
|
||||
@@ -0,0 +1,127 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
// SessionService отвечает за вход, проверку и отзыв сессий.
|
||||
type SessionService struct {
|
||||
users domain.UserRepository
|
||||
sessions domain.SessionRepository
|
||||
hasher PasswordHasher
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
// NewSessionService создаёт сервис с заданным TTL сессий.
|
||||
func NewSessionService(
|
||||
users domain.UserRepository,
|
||||
sessions domain.SessionRepository,
|
||||
hasher PasswordHasher,
|
||||
ttl time.Duration,
|
||||
) *SessionService {
|
||||
return &SessionService{
|
||||
users: users,
|
||||
sessions: sessions,
|
||||
hasher: hasher,
|
||||
ttl: ttl,
|
||||
}
|
||||
}
|
||||
|
||||
// Login проверяет username/password и создаёт новую сессию.
|
||||
// Возвращает сессию, открытый токен и пользователя.
|
||||
// Открытый токен уходит клиенту; в БД сохраняется только его SHA-256.
|
||||
func (s *SessionService) Login(ctx context.Context, username, password string) (*domain.Session, string, *domain.User, error) {
|
||||
user, err := s.users.GetByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return nil, "", nil, &domain.UnauthorizedError{Reason: "неверные учётные данные"}
|
||||
}
|
||||
return nil, "", nil, err
|
||||
}
|
||||
|
||||
ok, err := s.hasher.Verify(password, user.PasswordHash)
|
||||
if err != nil {
|
||||
return nil, "", nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, "", nil, &domain.UnauthorizedError{Reason: "неверные учётные данные"}
|
||||
}
|
||||
|
||||
token, err := generateToken()
|
||||
if err != nil {
|
||||
return nil, "", nil, err
|
||||
}
|
||||
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
now := time.Now().UTC()
|
||||
|
||||
session := &domain.Session{
|
||||
TokenHash: tokenHash[:],
|
||||
UserID: user.ID,
|
||||
ExpiresAt: now.Add(s.ttl),
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := s.sessions.Create(ctx, session); err != nil {
|
||||
return nil, "", nil, err
|
||||
}
|
||||
|
||||
return session, token, user, nil
|
||||
}
|
||||
|
||||
// Resolve проверяет токен и возвращает пользователя сессии.
|
||||
// Истёкший, отозванный или неизвестный токен - UnauthorizedError по контракту
|
||||
func (s *SessionService) Resolve(ctx context.Context, token string) (*domain.User, error) {
|
||||
if token == "" {
|
||||
return nil, &domain.UnauthorizedError{Reason: "пустой токен"}
|
||||
}
|
||||
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
|
||||
session, err := s.sessions.GetByTokenHash(ctx, tokenHash[:])
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return nil, &domain.UnauthorizedError{Reason: "неизвестный токен"}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !session.ExpiresAt.After(time.Now().UTC()) {
|
||||
return nil, &domain.UnauthorizedError{Reason: "сессия истекла"}
|
||||
}
|
||||
|
||||
user, err := s.users.GetByID(ctx, session.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return nil, &domain.UnauthorizedError{Reason: "пользователь сессии не найден"}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// Revoke удаляет сессию по токену.
|
||||
func (s *SessionService) Revoke(ctx context.Context, token string) error {
|
||||
if token == "" {
|
||||
return nil
|
||||
}
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
return s.sessions.DeleteByTokenHash(ctx, tokenHash[:])
|
||||
}
|
||||
|
||||
// generateToken возвращает 32 случайных байта в base64url без паддинга=.
|
||||
func generateToken() (string, error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", fmt.Errorf("генерация токена: %w", err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type UserService struct {
|
||||
users domain.UserRepository
|
||||
hasher PasswordHasher
|
||||
}
|
||||
|
||||
func NewUserService(users domain.UserRepository, hasher PasswordHasher) *UserService {
|
||||
return &UserService{users: users, hasher: hasher}
|
||||
}
|
||||
|
||||
func (s *UserService) Create(ctx context.Context, username, displayName, password string) (*domain.User, error) {
|
||||
if !usernamePattern.MatchString(username) {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "username",
|
||||
Message: "должен соответствовать ^[a-z0-9_]{3,32}$",
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(displayName) == "" {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "display_name",
|
||||
Message: "не может состоять только из пробелов",
|
||||
}
|
||||
}
|
||||
if utf8.RuneCountInString(displayName) > 100 {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "display_name",
|
||||
Message: "не более 100 символов",
|
||||
}
|
||||
}
|
||||
|
||||
passwordRunes := utf8.RuneCountInString(password)
|
||||
if passwordRunes < 12 || passwordRunes > 128 {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "password",
|
||||
Message: "длина 12–128 символов",
|
||||
}
|
||||
}
|
||||
|
||||
hash, err := s.hasher.Hash(password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
u := &domain.User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
PasswordHash: hash,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if err := s.users.Create(ctx, u); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *UserService) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
return s.users.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *UserService) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
|
||||
return s.users.GetByUsername(ctx, username)
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func (r *ChatRepo) Create(ctx context.Context, chat *domain.Chat) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
stored := *chat
|
||||
stored.MemberIDs = append([]string(nil), chat.MemberIDs...)
|
||||
r.chats[chat.ID] = &stored
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ChatRepo) GetByID(ctx context.Context, id string) (*domain.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
c, ok := r.chats[id]
|
||||
if !ok {
|
||||
return nil, &domain.NotFoundError{Entity: "chat", ID: id}
|
||||
}
|
||||
copy := *c
|
||||
copy.MemberIDs = append([]string(nil), c.MemberIDs...)
|
||||
return ©, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepo) ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
scope := "chats:" + userID
|
||||
|
||||
all := make([]domain.Chat, 0)
|
||||
for _, c := range r.chats {
|
||||
for _, m := range c.MemberIDs {
|
||||
if m == userID {
|
||||
copy := *c
|
||||
copy.MemberIDs = append([]string(nil), c.MemberIDs...)
|
||||
all = append(all, copy)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
slices.SortFunc(all, func(a, b domain.Chat) int {
|
||||
if lessThan(a.CreatedAt, a.ID, b.CreatedAt, b.ID) {
|
||||
return -1
|
||||
}
|
||||
if lessThan(b.CreatedAt, b.ID, a.CreatedAt, a.ID) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
start := 0
|
||||
if cursor != nil {
|
||||
t, id, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
start = len(all)
|
||||
for i, c := range all {
|
||||
if lessThan(t, id, c.CreatedAt, c.ID) {
|
||||
start = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if start >= len(all) {
|
||||
return []domain.Chat{}, nil, nil
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(all) {
|
||||
end = len(all)
|
||||
}
|
||||
page := all[start:end]
|
||||
|
||||
var next *string
|
||||
if end < len(all) {
|
||||
last := page[len(page)-1]
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func encodeCursor(scope string, createdAt time.Time, id string) string {
|
||||
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
parts := strings.SplitN(string(data), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
if parts[0] != expectedScope {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
return t, parts[2], nil
|
||||
}
|
||||
|
||||
func badCursor() error {
|
||||
return &domain.ValidationError{
|
||||
Field: "cursor",
|
||||
Message: "некорректный формат",
|
||||
}
|
||||
}
|
||||
|
||||
func lessThan(aTime time.Time, aID string, bTime time.Time, bID string) bool {
|
||||
if aTime.Equal(bTime) {
|
||||
return aID < bID
|
||||
}
|
||||
return aTime.Before(bTime)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func (r *MessageRepo) Create(ctx context.Context, message *domain.Message) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
stored := *message
|
||||
r.messages[message.ChatID] = append(r.messages[message.ChatID], stored)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
scope := "messages:" + chatID
|
||||
|
||||
var (
|
||||
afterTime time.Time
|
||||
afterID string
|
||||
hasCursor bool
|
||||
)
|
||||
if cursor != nil {
|
||||
t, id, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
afterTime = t
|
||||
afterID = id
|
||||
hasCursor = true
|
||||
}
|
||||
|
||||
src := r.messages[chatID]
|
||||
if len(src) == 0 {
|
||||
return []domain.Message{}, nil, nil
|
||||
}
|
||||
|
||||
all := make([]domain.Message, len(src))
|
||||
copy(all, src)
|
||||
|
||||
slices.SortFunc(all, func(a, b domain.Message) int {
|
||||
if lessThan(a.CreatedAt, a.ID, b.CreatedAt, b.ID) {
|
||||
return -1
|
||||
}
|
||||
if lessThan(b.CreatedAt, b.ID, a.CreatedAt, a.ID) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
start := 0
|
||||
if hasCursor {
|
||||
start = len(all)
|
||||
for i, m := range all {
|
||||
if lessThan(afterTime, afterID, m.CreatedAt, m.ID) {
|
||||
start = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if start >= len(all) {
|
||||
return []domain.Message{}, nil, nil
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(all) {
|
||||
end = len(all)
|
||||
}
|
||||
page := all[start:end]
|
||||
|
||||
var next *string
|
||||
if end < len(all) {
|
||||
last := page[len(page)-1]
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type Storage struct {
|
||||
mu sync.RWMutex
|
||||
users map[string]*domain.User
|
||||
chats map[string]*domain.Chat
|
||||
messages map[string][]domain.Message
|
||||
}
|
||||
|
||||
func New() *Storage {
|
||||
return &Storage{
|
||||
users: make(map[string]*domain.User),
|
||||
chats: make(map[string]*domain.Chat),
|
||||
messages: make(map[string][]domain.Message),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Storage) Users() *UserRepo { return &UserRepo{s} }
|
||||
func (s *Storage) Chats() *ChatRepo { return &ChatRepo{s} }
|
||||
func (s *Storage) Messages() *MessageRepo { return &MessageRepo{s} }
|
||||
|
||||
type UserRepo struct{ *Storage }
|
||||
type ChatRepo struct{ *Storage }
|
||||
type MessageRepo struct{ *Storage }
|
||||
|
||||
var _ domain.UserRepository = (*UserRepo)(nil)
|
||||
var _ domain.ChatRepository = (*ChatRepo)(nil)
|
||||
var _ domain.MessageRepository = (*MessageRepo)(nil)
|
||||
@@ -0,0 +1,59 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func (r *UserRepo) Create(ctx context.Context, user *domain.User) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
for _, u := range r.users {
|
||||
if u.Username == user.Username {
|
||||
return &domain.AlreadyExistsError{
|
||||
Entity: "user",
|
||||
Field: "username",
|
||||
Value: user.Username,
|
||||
}
|
||||
}
|
||||
}
|
||||
stored := *user
|
||||
r.users[user.ID] = &stored
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
u, ok := r.users[id]
|
||||
if !ok {
|
||||
return nil, &domain.NotFoundError{Entity: "user", ID: id}
|
||||
}
|
||||
copy := *u
|
||||
return ©, nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
for _, u := range r.users {
|
||||
if u.Username == username {
|
||||
copy := *u
|
||||
return ©, nil
|
||||
}
|
||||
}
|
||||
return nil, &domain.NotFoundError{Entity: "user", ID: username}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type ChatRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatRepo(pool *pgxpool.Pool) *ChatRepo {
|
||||
return &ChatRepo{pool: pool}
|
||||
}
|
||||
|
||||
// Create атомарно создаёт чат и его участников.
|
||||
func (r *ChatRepo) Create(ctx context.Context, chat *domain.Chat) error {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
const qChat = `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)`
|
||||
if _, err := tx.Exec(ctx, qChat, chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{Field: "chat", Message: "нарушено ограничение целостности"}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
const qMember = `INSERT INTO chat_members (chat_id, user_id) VALUES ($1::uuid, $2::uuid)`
|
||||
for _, uid := range chat.MemberIDs {
|
||||
if _, err := tx.Exec(ctx, qMember, chat.ID, uid); err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "неизвестный участник " + uid,
|
||||
}
|
||||
}
|
||||
if uniqueViolation(err) {
|
||||
return &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "дубликаты запрещены",
|
||||
}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
}
|
||||
|
||||
return mapError(tx.Commit(ctx))
|
||||
}
|
||||
|
||||
func (r *ChatRepo) GetByID(ctx context.Context, id string) (*domain.Chat, error) {
|
||||
const q = `SELECT id, title, created_at FROM chats WHERE id = $1::uuid`
|
||||
c := &domain.Chat{}
|
||||
err := r.pool.QueryRow(ctx, q, id).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "chat", id)
|
||||
}
|
||||
members, err := r.loadMembers(ctx, []string{c.ID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.MemberIDs = members[c.ID]
|
||||
if c.MemberIDs == nil {
|
||||
c.MemberIDs = []string{}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepo) ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) {
|
||||
scope := "chats:" + userID
|
||||
|
||||
var (
|
||||
afterTime time.Time
|
||||
afterID string
|
||||
hasCursor bool
|
||||
)
|
||||
if cursor != nil {
|
||||
t, id, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
afterTime = t
|
||||
afterID = id
|
||||
hasCursor = true
|
||||
}
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if hasCursor {
|
||||
const q = `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1::uuid
|
||||
AND (c.created_at, c.id) > ($2, $3::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, userID, afterTime, afterID, limit+1)
|
||||
} else {
|
||||
const q = `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1::uuid
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, userID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
page := make([]domain.Chat, 0, limit)
|
||||
for rows.Next() {
|
||||
var c domain.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, nil, mapError(err)
|
||||
}
|
||||
page = append(page, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, mapError(err)
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(page) > limit {
|
||||
page = page[:limit]
|
||||
last := page[len(page)-1]
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
|
||||
if len(page) > 0 {
|
||||
ids := make([]string, len(page))
|
||||
for i := range page {
|
||||
ids[i] = page[i].ID
|
||||
}
|
||||
members, err := r.loadMembers(ctx, ids)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for i := range page {
|
||||
if m, ok := members[page[i].ID]; ok {
|
||||
page[i].MemberIDs = m
|
||||
} else {
|
||||
page[i].MemberIDs = []string{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
// loadMembers одним запросом собирает участников для указанных чатов.
|
||||
func (r *ChatRepo) loadMembers(ctx context.Context, chatIDs []string) (map[string][]string, error) {
|
||||
if len(chatIDs) == 0 {
|
||||
return map[string][]string{}, nil
|
||||
}
|
||||
const q = `
|
||||
SELECT chat_id, user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = ANY($1::uuid[])
|
||||
ORDER BY chat_id, user_id
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, chatIDs)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
result := make(map[string][]string, len(chatIDs))
|
||||
for rows.Next() {
|
||||
var chatID, userID string
|
||||
if err := rows.Scan(&chatID, &userID); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
result[chatID] = append(result[chatID], userID)
|
||||
}
|
||||
return result, mapError(rows.Err())
|
||||
}
|
||||
|
||||
var _ domain.ChatRepository = (*ChatRepo)(nil)
|
||||
@@ -0,0 +1,46 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Взял за основу что в inmemery делал
|
||||
func encodeCursor(scope string, createdAt time.Time, id string) string {
|
||||
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
parts := strings.SplitN(string(data), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
if parts[0] != expectedScope {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
if _, err := uuid.Parse(parts[2]); err != nil {
|
||||
return time.Time{}, "", badCursor()
|
||||
}
|
||||
return t, parts[2], nil
|
||||
}
|
||||
|
||||
func badCursor() error {
|
||||
return &domain.ValidationError{
|
||||
Field: "cursor",
|
||||
Message: "некорректный формат",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
|
||||
"high-loud-apps-labs/migrations"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
URL string
|
||||
MaxConns int32
|
||||
MinConns int32
|
||||
MaxConnLifetime time.Duration
|
||||
MaxConnIdleTime time.Duration
|
||||
ConnectTimeout time.Duration
|
||||
}
|
||||
|
||||
func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
||||
if cfg.URL == "" {
|
||||
return nil, fmt.Errorf("DATABASE_URL пустой")
|
||||
}
|
||||
|
||||
poolCfg, err := pgxpool.ParseConfig(cfg.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("разбор DATABASE_URL: %w", err)
|
||||
}
|
||||
if cfg.MaxConns > 0 {
|
||||
poolCfg.MaxConns = cfg.MaxConns
|
||||
}
|
||||
if cfg.MinConns > 0 {
|
||||
poolCfg.MinConns = cfg.MinConns
|
||||
}
|
||||
if cfg.MaxConnLifetime > 0 {
|
||||
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
|
||||
}
|
||||
if cfg.MaxConnIdleTime > 0 {
|
||||
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
|
||||
}
|
||||
if cfg.ConnectTimeout > 0 {
|
||||
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
||||
}
|
||||
poolCfg.HealthCheckPeriod = 10 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("создание пула: %w", err)
|
||||
}
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping БД: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func RunMigrations(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
db := stdlib.OpenDBFromPool(pool)
|
||||
|
||||
goose.SetBaseFS(migrations.FS)
|
||||
if err := goose.SetDialect("postgres"); err != nil {
|
||||
return fmt.Errorf("goose dialect: %w", err)
|
||||
}
|
||||
if err := goose.UpContext(ctx, db, "."); err != nil {
|
||||
return fmt.Errorf("применение миграций: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type coded interface {
|
||||
Code() domain.ErrorCode
|
||||
}
|
||||
|
||||
// mapError переводит ошибки драйвера в доменные.
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var c coded
|
||||
if errors.As(err, &c) {
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return &domain.UnavailableError{Reason: "превышено время ожидания БД"}
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return &domain.UnavailableError{Reason: "запрос отменён"}
|
||||
}
|
||||
return &domain.UnavailableError{Reason: err.Error()}
|
||||
}
|
||||
|
||||
func notFound(err error, entity, id string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return &domain.NotFoundError{Entity: entity, ID: id}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func uniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
return pgErr.Code == pgerrcode.UniqueViolation
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func foreignKeyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
return pgErr.Code == pgerrcode.ForeignKeyViolation
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func checkViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
return pgErr.Code == pgerrcode.CheckViolation
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type MessageRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageRepo(pool *pgxpool.Pool) *MessageRepo {
|
||||
return &MessageRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessageRepo) Create(ctx context.Context, m *domain.Message) error {
|
||||
const q = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt)
|
||||
if err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return &domain.NotFoundError{Entity: "chat", ID: m.ChatID}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{Field: "text", Message: "нарушено ограничение"}
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (r *MessageRepo) CreateIdempotent(
|
||||
ctx context.Context,
|
||||
scope domain.IdempotencyScope,
|
||||
requestHash []byte,
|
||||
fresh *domain.Message,
|
||||
freshResponse []byte,
|
||||
ttl time.Duration,
|
||||
) (*domain.CreateIdempotentResult, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
// 1) Убираем просроченную запись, чтобы ON CONFLICT сработал
|
||||
// только на живой, а не на истёкшей строке.
|
||||
if _, err := tx.Exec(ctx, `
|
||||
DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4
|
||||
AND expires_at <= now()
|
||||
`, scope.UserID, scope.Method, scope.Path, scope.Key); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
// 2) Резервируем слот. Если параллельная реплика уже вставила —
|
||||
// Postgres заблокирует конфликтный INSERT и мы увидим RowsAffected=0
|
||||
// только после того, как конкурент закоммитит или откатится.
|
||||
expiresAt := time.Now().UTC().Add(ttl)
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO idempotency_keys
|
||||
(user_id, method, path, key, request_hash, response_status, response_body, expires_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8)
|
||||
ON CONFLICT (user_id, method, path, key) DO NOTHING
|
||||
`, scope.UserID, scope.Method, scope.Path, scope.Key,
|
||||
requestHash, http.StatusCreated, freshResponse, expiresAt)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
// 3) Слот занят — читаем сохранённый ответ в этой же транзакции.
|
||||
if tag.RowsAffected() == 0 {
|
||||
var (
|
||||
storedHash []byte
|
||||
storedStatus int
|
||||
storedBody []byte
|
||||
)
|
||||
err := tx.QueryRow(ctx, `
|
||||
SELECT request_hash, response_status, response_body
|
||||
FROM idempotency_keys
|
||||
WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4
|
||||
`, scope.UserID, scope.Method, scope.Path, scope.Key).
|
||||
Scan(&storedHash, &storedStatus, &storedBody)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(storedHash, requestHash) {
|
||||
return nil, &domain.IdempotencyConflictError{Key: scope.Key}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
return &domain.CreateIdempotentResult{
|
||||
Status: storedStatus,
|
||||
Body: storedBody,
|
||||
Replayed: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 4) Слот наш — вставляем сообщение в той же транзакции.
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
`, fresh.ID, fresh.ChatID, fresh.SenderID, fresh.Text, fresh.CreatedAt); err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return nil, &domain.NotFoundError{Entity: "chat", ID: fresh.ChatID}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return nil, &domain.ValidationError{Field: "text", Message: "нарушено ограничение"}
|
||||
}
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
return &domain.CreateIdempotentResult{
|
||||
Status: http.StatusCreated,
|
||||
Body: freshResponse,
|
||||
Replayed: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
|
||||
scope := "messages:" + chatID
|
||||
|
||||
var (
|
||||
afterTime time.Time
|
||||
afterID string
|
||||
hasCursor bool
|
||||
)
|
||||
if cursor != nil {
|
||||
t, id, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
afterTime = t
|
||||
afterID = id
|
||||
hasCursor = true
|
||||
}
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if hasCursor {
|
||||
const q = `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1::uuid
|
||||
AND (created_at, id) > ($2, $3::uuid)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, chatID, afterTime, afterID, limit+1)
|
||||
} else {
|
||||
const q = `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1::uuid
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err = r.pool.Query(ctx, q, chatID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
page := make([]domain.Message, 0, limit)
|
||||
for rows.Next() {
|
||||
var m domain.Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
page = append(page, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(page) > limit {
|
||||
page = page[:limit]
|
||||
last := page[len(page)-1]
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
var _ domain.MessageRepository = (*MessageRepo)(nil)
|
||||
@@ -0,0 +1,59 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type SessionRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewSessionRepo(pool *pgxpool.Pool) *SessionRepo {
|
||||
return &SessionRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error {
|
||||
const q = `
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at, created_at)
|
||||
VALUES ($1, $2::uuid, $3, $4)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, s.TokenHash, s.UserID, s.ExpiresAt, s.CreatedAt)
|
||||
if err != nil {
|
||||
if uniqueViolation(err) {
|
||||
return &domain.AlreadyExistsError{
|
||||
Entity: "session",
|
||||
Field: "token_hash",
|
||||
Value: "",
|
||||
}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) {
|
||||
const q = `
|
||||
SELECT token_hash, user_id, expires_at, created_at
|
||||
FROM sessions
|
||||
WHERE token_hash = $1
|
||||
`
|
||||
s := &domain.Session{}
|
||||
err := r.pool.QueryRow(ctx, q, tokenHash).
|
||||
Scan(&s.TokenHash, &s.UserID, &s.ExpiresAt, &s.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "session", "")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error {
|
||||
const q = `DELETE FROM sessions WHERE token_hash = $1`
|
||||
_, err := r.pool.Exec(ctx, q, tokenHash)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
var _ domain.SessionRepository = (*SessionRepo)(nil)
|
||||
@@ -0,0 +1,18 @@
|
||||
package postgres
|
||||
|
||||
import "github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
type Storage struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *Storage {
|
||||
return &Storage{pool: pool}
|
||||
}
|
||||
|
||||
func (s *Storage) Pool() *pgxpool.Pool { return s.pool }
|
||||
|
||||
func (s *Storage) Users() *UserRepo { return &UserRepo{pool: s.pool} }
|
||||
func (s *Storage) Chats() *ChatRepo { return &ChatRepo{pool: s.pool} }
|
||||
func (s *Storage) Messages() *MessageRepo { return &MessageRepo{pool: s.pool} }
|
||||
func (s *Storage) Sessions() *SessionRepo { return &SessionRepo{pool: s.pool} }
|
||||
@@ -0,0 +1,76 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type UserRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRepo(pool *pgxpool.Pool) *UserRepo {
|
||||
return &UserRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *UserRepo) Create(ctx context.Context, user *domain.User) error {
|
||||
const q = `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q,
|
||||
user.ID, user.Username, user.DisplayName, user.PasswordHash, user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
if uniqueViolation(err) {
|
||||
return &domain.AlreadyExistsError{
|
||||
Entity: "user",
|
||||
Field: "username",
|
||||
Value: user.Username,
|
||||
}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{
|
||||
Field: "user",
|
||||
Message: "нарушено ограничение целостности",
|
||||
}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
const q = `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE id = $1::uuid
|
||||
`
|
||||
u := &domain.User{}
|
||||
err := r.pool.QueryRow(ctx, q, id).
|
||||
Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "user", id)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
|
||||
const q = `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
u := &domain.User{}
|
||||
err := r.pool.QueryRow(ctx, q, username).
|
||||
Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err, "user", username)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
var _ domain.UserRepository = (*UserRepo)(nil)
|
||||
@@ -0,0 +1,33 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func NewClient(url string) (*redis.Client, error) {
|
||||
opt, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("разбор URL: %w", err)
|
||||
}
|
||||
|
||||
opt.DialTimeout = 700 * time.Millisecond
|
||||
opt.ReadTimeout = 700 * time.Millisecond
|
||||
opt.WriteTimeout = 700 * time.Millisecond
|
||||
opt.MaxRetries = 1
|
||||
opt.PoolSize = 10
|
||||
opt.ConnMaxIdleTime = time.Minute
|
||||
|
||||
client := redis.NewClient(opt)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, fmt.Errorf("ping: %w", err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type coded interface {
|
||||
Code() domain.ErrorCode
|
||||
}
|
||||
|
||||
// mapError переводит ошибки драйвера в доменные.
|
||||
// Любая недоступность redis (dial/read/write/context) → UnavailableError (503).
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var c coded
|
||||
if errors.As(err, &c) {
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return &domain.UnavailableError{Reason: "превышено время ожидания redis"}
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return &domain.UnavailableError{Reason: "запрос отменён"}
|
||||
}
|
||||
return &domain.UnavailableError{Reason: err.Error()}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
const sessionKeyPrefix = "session:"
|
||||
|
||||
type SessionRepo struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionRepo(client *redis.Client) *SessionRepo {
|
||||
return &SessionRepo{client: client}
|
||||
}
|
||||
|
||||
type sessionValue struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (r *SessionRepo) key(tokenHash []byte) string {
|
||||
return sessionKeyPrefix + hex.EncodeToString(tokenHash)
|
||||
}
|
||||
|
||||
func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error {
|
||||
ttl := time.Until(s.ExpiresAt)
|
||||
if ttl <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
data, err := json.Marshal(sessionValue{
|
||||
UserID: s.UserID,
|
||||
ExpiresAt: s.ExpiresAt.UTC(),
|
||||
CreatedAt: s.CreatedAt.UTC(),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("сериализация сессии: %w", err)
|
||||
}
|
||||
|
||||
return mapError(r.client.Set(ctx, r.key(s.TokenHash), data, ttl).Err())
|
||||
}
|
||||
|
||||
func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) {
|
||||
data, err := r.client.Get(ctx, r.key(tokenHash)).Bytes()
|
||||
if err != nil {
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, &domain.NotFoundError{Entity: "session"}
|
||||
}
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
var sv sessionValue
|
||||
if err := json.Unmarshal(data, &sv); err != nil {
|
||||
return nil, fmt.Errorf("разбор сессии: %w", err)
|
||||
}
|
||||
|
||||
return &domain.Session{
|
||||
TokenHash: tokenHash,
|
||||
UserID: sv.UserID,
|
||||
ExpiresAt: sv.ExpiresAt,
|
||||
CreatedAt: sv.CreatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error {
|
||||
return mapError(r.client.Del(ctx, r.key(tokenHash)).Err())
|
||||
}
|
||||
|
||||
var _ domain.SessionRepository = (*SessionRepo)(nil)
|
||||
Reference in New Issue
Block a user