lab3- оценка 4
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
func CheckPassword(password, hash string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func GenerateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.URLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func HashToken(token string) string {
|
||||
h := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func SecureCompare(a, b string) bool {
|
||||
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
|
||||
}
|
||||
|
||||
func IsSessionExpired(expiresAt time.Time) bool {
|
||||
return time.Now().After(expiresAt)
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab3-fork/src/internal/auth"
|
||||
"mtusi2026lab3-fork/src/internal/model"
|
||||
"mtusi2026lab3-fork/src/internal/store"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type CtxKey string
|
||||
|
||||
const RequestIDKey CtxKey = "request_id"
|
||||
const UserIDKey CtxKey = "user_id"
|
||||
|
||||
type SessionStore interface {
|
||||
Get(ctx context.Context, tokenHash string) (string, error)
|
||||
Set(ctx context.Context, userID, tokenHash string, ttl time.Duration) error
|
||||
Delete(ctx context.Context, tokenHash string) error
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
store store.Store
|
||||
sessionStore SessionStore
|
||||
sessionTTL time.Duration
|
||||
}
|
||||
|
||||
func New(s store.Store, ss SessionStore, ttl time.Duration) *Handler {
|
||||
return &Handler{store: s, sessionStore: ss, sessionTTL: ttl}
|
||||
}
|
||||
|
||||
func userToMap(u *model.User) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"id": u.ID,
|
||||
"username": u.Username,
|
||||
"display_name": u.DisplayName,
|
||||
"created_at": u.CreatedAt.UTC().Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
func respondError(w http.ResponseWriter, r *http.Request, code int, errorCode string) {
|
||||
requestID, _ := r.Context().Value(RequestIDKey).(string)
|
||||
log.Printf("ERROR: %d - %s [request_id=%s]", code, errorCode, requestID)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"error": map[string]string{"code": errorCode, "message": http.StatusText(code), "request_id": requestID},
|
||||
})
|
||||
}
|
||||
|
||||
func respondJSON(w http.ResponseWriter, code int, data interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func checkContentType(r *http.Request) bool {
|
||||
ct := r.Header.Get("Content-Type")
|
||||
return ct == "application/json" || strings.HasPrefix(ct, "application/json;")
|
||||
}
|
||||
|
||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
if !checkContentType(r) {
|
||||
respondError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&req); err != nil {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
if len(req.Password) < 12 || len(req.Password) > 128 {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
pwHash, err := auth.HashPassword(req.Password)
|
||||
if err != nil {
|
||||
respondError(w, r, http.StatusInternalServerError, "internal_error")
|
||||
return
|
||||
}
|
||||
user, err := h.store.CreateUser(r.Context(), req.Username, req.DisplayName, pwHash)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
respondError(w, r, http.StatusConflict, "conflict")
|
||||
} else {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
return
|
||||
}
|
||||
respondJSON(w, http.StatusCreated, userToMap(user))
|
||||
}
|
||||
|
||||
func (h *Handler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(authHeader, "Basic ") {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
payload, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Basic "))
|
||||
if err != nil {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
parts := strings.SplitN(string(payload), ":", 2)
|
||||
if len(parts) != 2 {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
username, password := parts[0], parts[1]
|
||||
user, err := h.store.GetUserByUsername(r.Context(), username)
|
||||
if err != nil || !auth.CheckPassword(password, user.PasswordHash) {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
token, err := auth.GenerateToken()
|
||||
if err != nil {
|
||||
respondError(w, r, http.StatusInternalServerError, "internal_error")
|
||||
return
|
||||
}
|
||||
tokenHash := auth.HashToken(token)
|
||||
expiresAt := time.Now().Add(h.sessionTTL)
|
||||
if err := h.sessionStore.Set(r.Context(), user.ID, tokenHash, h.sessionTTL); err != nil {
|
||||
respondError(w, r, http.StatusServiceUnavailable, "unavailable")
|
||||
return
|
||||
}
|
||||
_, _ = h.store.CreateSession(r.Context(), user.ID, tokenHash, expiresAt)
|
||||
respondJSON(w, http.StatusCreated, map[string]interface{}{
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expiresAt.UTC().Format(time.RFC3339),
|
||||
"user": userToMap(user),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteSession(w http.ResponseWriter, r *http.Request) {
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
tokenHash := auth.HashToken(token)
|
||||
|
||||
if err := h.store.DeleteSession(r.Context(), tokenHash); err != nil {
|
||||
respondError(w, r, http.StatusServiceUnavailable, "unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.sessionStore.Delete(r.Context(), tokenHash); err != nil {
|
||||
respondError(w, r, http.StatusServiceUnavailable, "unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) BearerAuthMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
tokenHash := auth.HashToken(strings.TrimPrefix(authHeader, "Bearer "))
|
||||
userID, err := h.sessionStore.Get(r.Context(), tokenHash)
|
||||
if err != nil {
|
||||
sess, errPg := h.store.GetSession(r.Context(), tokenHash)
|
||||
if errPg != nil || auth.IsSessionExpired(sess.ExpiresAt) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
userID = sess.UserID
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), UserIDKey, userID)))
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := r.Context().Value(UserIDKey).(string)
|
||||
if !ok {
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
user, err := h.store.GetUserByID(r.Context(), userID)
|
||||
if err != nil {
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
respondJSON(w, http.StatusOK, userToMap(user))
|
||||
}
|
||||
|
||||
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
if !checkContentType(r) {
|
||||
respondError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type")
|
||||
return
|
||||
}
|
||||
userID, ok := r.Context().Value(UserIDKey).(string)
|
||||
if !ok {
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&req); err != nil {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
isMember := false
|
||||
for _, id := range req.MemberIDs {
|
||||
if id == userID {
|
||||
isMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isMember {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
chat, err := h.store.CreateChat(r.Context(), req.Title, req.MemberIDs)
|
||||
if err != nil {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
if chat.MemberIDs == nil {
|
||||
chat.MemberIDs = []string{}
|
||||
}
|
||||
respondJSON(w, http.StatusCreated, chat)
|
||||
}
|
||||
|
||||
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := r.Context().Value(UserIDKey).(string)
|
||||
if !ok {
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
limit := 50
|
||||
if ls := r.URL.Query().Get("limit"); ls != "" {
|
||||
p, err := strconv.Atoi(ls)
|
||||
if err != nil || p < 1 || p > 100 {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
limit = p
|
||||
}
|
||||
chats, nextCursor, err := h.store.ListChats(r.Context(), userID, limit, r.URL.Query().Get("cursor"))
|
||||
if err != nil {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
if chats == nil {
|
||||
chats = []*model.Chat{}
|
||||
}
|
||||
for _, c := range chats {
|
||||
if c.MemberIDs == nil {
|
||||
c.MemberIDs = []string{}
|
||||
}
|
||||
}
|
||||
respondJSON(w, http.StatusOK, map[string]interface{}{"items": chats, "next_cursor": nextCursor})
|
||||
}
|
||||
|
||||
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := r.Context().Value(UserIDKey).(string)
|
||||
if !ok {
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
chat, err := h.store.GetChat(r.Context(), chi.URLParam(r, "chat_id"), userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
respondError(w, r, http.StatusNotFound, "not_found")
|
||||
} else {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
return
|
||||
}
|
||||
if chat.MemberIDs == nil {
|
||||
chat.MemberIDs = []string{}
|
||||
}
|
||||
respondJSON(w, http.StatusOK, chat)
|
||||
}
|
||||
|
||||
// SendMessage — лаба 3: обязателен Idempotency-Key.
|
||||
func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
if !checkContentType(r) {
|
||||
respondError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type")
|
||||
return
|
||||
}
|
||||
userID, ok := r.Context().Value(UserIDKey).(string)
|
||||
if !ok {
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
idemKey := r.Header.Get("Idempotency-Key")
|
||||
if idemKey == "" || len(idemKey) > 255 {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
chatID := chi.URLParam(r, "chat_id")
|
||||
|
||||
var req struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&req); err != nil {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
|
||||
// Канонический хеш тела: только значимые поля, стабильный порядок.
|
||||
canonical, _ := json.Marshal(map[string]string{"text": req.Text})
|
||||
requestHash := sha256Hex(canonical)
|
||||
|
||||
path := "/api/v1/chats/" + chatID + "/messages"
|
||||
msg, err := h.store.SendMessageIdempotent(r.Context(), chatID, userID, req.Text, idemKey, path, requestHash)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrConflict):
|
||||
respondError(w, r, http.StatusConflict, "conflict")
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
respondError(w, r, http.StatusNotFound, "not_found")
|
||||
default:
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
return
|
||||
}
|
||||
respondJSON(w, http.StatusCreated, msg)
|
||||
}
|
||||
|
||||
func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := r.Context().Value(UserIDKey).(string)
|
||||
if !ok {
|
||||
respondError(w, r, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
limit := 50
|
||||
if ls := r.URL.Query().Get("limit"); ls != "" {
|
||||
p, err := strconv.Atoi(ls)
|
||||
if err != nil || p < 1 || p > 100 {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
limit = p
|
||||
}
|
||||
messages, nextCursor, err := h.store.GetMessages(r.Context(), chi.URLParam(r, "chat_id"), userID, r.URL.Query().Get("cursor"), limit)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
respondError(w, r, http.StatusNotFound, "not_found")
|
||||
} else {
|
||||
respondError(w, r, http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
return
|
||||
}
|
||||
if messages == nil {
|
||||
messages = []*model.Message{}
|
||||
}
|
||||
respondJSON(w, http.StatusOK, map[string]interface{}{"items": messages, "next_cursor": nextCursor})
|
||||
}
|
||||
|
||||
func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) {
|
||||
respondJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) {
|
||||
respondJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func sha256Hex(b []byte) string {
|
||||
h := sha256.Sum256(b)
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
PasswordHash string `json:"-"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
TokenHash string `json:"-"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// IdempotencyKey — запись ключа идемпотентности для POST сообщений (lab3).
|
||||
type IdempotencyKey struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
Method string `json:"method"`
|
||||
Path string `json:"path"`
|
||||
Key string `json:"key"`
|
||||
RequestHash string `json:"request_hash"`
|
||||
ResponseCode int `json:"response_code"`
|
||||
ResponseBody []byte `json:"response_body"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrSessionNotFound = errors.New("session_not_found")
|
||||
ErrRedisDown = errors.New("redis_unavailable")
|
||||
)
|
||||
|
||||
// RedisStore реализует handler.SessionStore (Get/Set/Delete).
|
||||
// Криптография токенов живёт в пакете auth — здесь только хранение.
|
||||
type RedisStore struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewRedisStore(redisURL string, ttl time.Duration) (*RedisStore, error) {
|
||||
opts, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse redis url: %w", err)
|
||||
}
|
||||
|
||||
opts.DialTimeout = 3 * time.Second
|
||||
opts.ReadTimeout = 3 * time.Second
|
||||
opts.WriteTimeout = 3 * time.Second
|
||||
opts.PoolSize = 20
|
||||
opts.MinIdleConns = 5
|
||||
|
||||
client := redis.NewClient(opts)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
return nil, fmt.Errorf("redis ping: %w", err)
|
||||
}
|
||||
|
||||
return &RedisStore{client: client}, nil
|
||||
}
|
||||
|
||||
func (s *RedisStore) Close() error {
|
||||
return s.client.Close()
|
||||
}
|
||||
|
||||
func (s *RedisStore) Set(ctx context.Context, userID, tokenHash string, ttl time.Duration) error {
|
||||
key := fmt.Sprintf("session:%s", tokenHash)
|
||||
if err := s.client.Set(ctx, key, userID, ttl).Err(); err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrRedisDown, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RedisStore) Get(ctx context.Context, tokenHash string) (string, error) {
|
||||
if tokenHash == "" {
|
||||
return "", ErrSessionNotFound
|
||||
}
|
||||
key := fmt.Sprintf("session:%s", tokenHash)
|
||||
userID, err := s.client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return "", ErrSessionNotFound
|
||||
}
|
||||
return "", fmt.Errorf("%w: %v", ErrRedisDown, err)
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
func (s *RedisStore) Delete(ctx context.Context, tokenHash string) error {
|
||||
key := fmt.Sprintf("session:%s", tokenHash)
|
||||
if err := s.client.Del(ctx, key).Err(); err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrRedisDown, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RedisStore) IsAvailable(ctx context.Context) bool {
|
||||
return s.client.Ping(ctx).Err() == nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
username VARCHAR(32) NOT NULL UNIQUE,
|
||||
display_name VARCHAR(100) NOT NULL,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT username_format CHECK (username ~ '^[a-z0-9_]{3,32}$')
|
||||
);
|
||||
|
||||
CREATE INDEX idx_users_username ON users(username);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
title VARCHAR(100) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_chat_members_user ON chat_members(user_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
text TEXT NOT NULL CHECK (length(text) >= 1 AND length(text) <= 4000),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_messages_chat_created ON messages(chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
token_hash VARCHAR(64) NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_sessions_token ON sessions(token_hash);
|
||||
CREATE INDEX idx_sessions_user ON sessions(user_id);
|
||||
CREATE INDEX idx_sessions_expires ON sessions(expires_at);
|
||||
@@ -0,0 +1,19 @@
|
||||
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
method TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
request_hash TEXT NOT NULL, -- SHA-256 hex canonical JSON body
|
||||
response_code INT NOT NULL,
|
||||
response_body JSONB NOT NULL, -- сохранённый Message для реплея
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
expires_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + INTERVAL '24 hours',
|
||||
UNIQUE (user_id, method, path, key)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_idem_expires ON idempotency_keys (expires_at);
|
||||
|
||||
-- Сообщения связываем с ключом, чтобы при реплее вернуть тот же объект
|
||||
ALTER TABLE messages
|
||||
ADD COLUMN IF NOT EXISTS idempotency_key_id UUID REFERENCES idempotency_keys(id) ON DELETE SET NULL;
|
||||
@@ -0,0 +1,565 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab3-fork/src/internal/model"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
|
||||
var (
|
||||
ErrInvalidRequest = errors.New("invalid_request")
|
||||
ErrNotFound = errors.New("not_found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
)
|
||||
|
||||
// Миграционный advisory lock: фиксированный 64-битный ID, чтобы две реплики
|
||||
// не применяли миграции одновременно.
|
||||
const migrationAdvisoryLockID int64 = 7272727272727272
|
||||
|
||||
type Store interface {
|
||||
CreateUser(ctx context.Context, username, displayName, passwordHash string) (*model.User, error)
|
||||
GetUserByID(ctx context.Context, id string) (*model.User, error)
|
||||
GetUserByUsername(ctx context.Context, username string) (*model.User, error)
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string) (*model.Chat, error)
|
||||
GetChat(ctx context.Context, chatID, userID string) (*model.Chat, error)
|
||||
ListChats(ctx context.Context, userID string, limit int, cursor string) ([]*model.Chat, *string, error)
|
||||
AddMessage(ctx context.Context, chatID, senderID, text string) (*model.Message, error)
|
||||
SendMessageIdempotent(ctx context.Context, chatID, senderID, text, idemKey, path, requestHash string) (*model.Message, error)
|
||||
GetMessages(ctx context.Context, chatID, userID, cursor string, limit int) ([]*model.Message, *string, error)
|
||||
CreateSession(ctx context.Context, userID, tokenHash string, expiresAt time.Time) (*model.Session, error)
|
||||
GetSession(ctx context.Context, tokenHash string) (*model.Session, error)
|
||||
DeleteSession(ctx context.Context, tokenHash string) error
|
||||
}
|
||||
|
||||
type PostgresStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewPostgres(connString string) (*PostgresStore, error) {
|
||||
config, err := pgxpool.ParseConfig(connString)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse config: %w", err)
|
||||
}
|
||||
config.MaxConns = 25
|
||||
config.MinConns = 5
|
||||
config.MaxConnLifetime = 30 * time.Minute
|
||||
config.MaxConnIdleTime = 5 * time.Minute
|
||||
config.HealthCheckPeriod = 30 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
store := &PostgresStore{pool: pool}
|
||||
if err := store.applyMigrations(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("apply migrations: %w", err)
|
||||
}
|
||||
|
||||
return store, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
// applyMigrations сериализован advisory-локом: первая реплика применяет,
|
||||
// вторая ждёт и видит уже применённые версии (идемпотентно).
|
||||
func (s *PostgresStore) applyMigrations(ctx context.Context) error {
|
||||
conn, err := s.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("acquire conn for lock: %w", err)
|
||||
}
|
||||
defer conn.Release()
|
||||
|
||||
if _, err := conn.Exec(ctx, `SELECT pg_advisory_lock($1)`, migrationAdvisoryLockID); err != nil {
|
||||
return fmt.Errorf("advisory lock: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, migrationAdvisoryLockID)
|
||||
}()
|
||||
|
||||
_, err = conn.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INTEGER PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create migrations table: %w", err)
|
||||
}
|
||||
|
||||
var lastVersion int
|
||||
err = conn.QueryRow(ctx, `SELECT COALESCE(MAX(version), 0) FROM schema_migrations`).Scan(&lastVersion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get last version: %w", err)
|
||||
}
|
||||
|
||||
entries, err := migrationsFS.ReadDir("migrations")
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migrations: %w", err)
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(entry.Name(), "%d_", &version); err != nil {
|
||||
continue
|
||||
}
|
||||
if version <= lastVersion {
|
||||
log.Printf("INFO: Skipping migration %s (already applied)", entry.Name())
|
||||
continue
|
||||
}
|
||||
content, err := migrationsFS.ReadFile("migrations/" + entry.Name())
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migration %s: %w", entry.Name(), err)
|
||||
}
|
||||
if _, err := conn.Exec(ctx, string(content)); err != nil {
|
||||
return fmt.Errorf("execute migration %s: %w", entry.Name(), err)
|
||||
}
|
||||
if _, err := conn.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, version); err != nil {
|
||||
return fmt.Errorf("insert migration version: %w", err)
|
||||
}
|
||||
log.Printf("INFO: Applied migration %s", entry.Name())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateUser(ctx context.Context, username, displayName, passwordHash string) (*model.User, error) {
|
||||
var user model.User
|
||||
query := `INSERT INTO users (username, display_name, password_hash) VALUES ($1, $2, $3) RETURNING id, username, display_name, created_at`
|
||||
err := s.pool.QueryRow(ctx, query, username, displayName, passwordHash).Scan(
|
||||
&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
return nil, fmt.Errorf("insert user: %w", err)
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetUserByID(ctx context.Context, id string) (*model.User, error) {
|
||||
var user model.User
|
||||
query := `SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1`
|
||||
err := s.pool.QueryRow(ctx, query, id).Scan(
|
||||
&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get user by id: %w", err)
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetUserByUsername(ctx context.Context, username string) (*model.User, error) {
|
||||
var user model.User
|
||||
query := `SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1`
|
||||
err := s.pool.QueryRow(ctx, query, username).Scan(
|
||||
&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get user by username: %w", err)
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateChat(ctx context.Context, title string, memberIDs []string) (*model.Chat, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var chat model.Chat
|
||||
if err := tx.QueryRow(ctx, `INSERT INTO chats (title) VALUES ($1) RETURNING id, created_at`, title).
|
||||
Scan(&chat.ID, &chat.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
for _, userID := range memberIDs {
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`, chat.ID, userID); err != nil {
|
||||
return nil, fmt.Errorf("insert member %s: %w", userID, err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
|
||||
chat.Title = title
|
||||
chat.MemberIDs = memberIDs
|
||||
if chat.MemberIDs == nil {
|
||||
chat.MemberIDs = []string{}
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
return &chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetChat(ctx context.Context, chatID, userID string) (*model.Chat, error) {
|
||||
var isMember bool
|
||||
if err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID).Scan(&isMember); err != nil {
|
||||
return nil, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
if !isMember {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
var chat model.Chat
|
||||
if err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, chatID).
|
||||
Scan(&chat.ID, &chat.Title, &chat.CreatedAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get chat: %w", err)
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
chat.MemberIDs = []string{}
|
||||
|
||||
rows, err := s.pool.Query(ctx, `SELECT user_id FROM chat_members WHERE chat_id = $1`, chatID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get members: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var m string
|
||||
if err := rows.Scan(&m); err != nil {
|
||||
return nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
chat.MemberIDs = append(chat.MemberIDs, m)
|
||||
}
|
||||
return &chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) ListChats(ctx context.Context, userID string, limit int, cursor string) ([]*model.Chat, *string, error) {
|
||||
fetchLimit := limit + 1 // +1, чтобы понять, есть ли следующая страница
|
||||
var query string
|
||||
var args []interface{}
|
||||
|
||||
if cursor == "" {
|
||||
query = `SELECT c.id, c.title, c.created_at FROM chats c
|
||||
INNER JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = $1 ORDER BY c.created_at, c.id LIMIT $2`
|
||||
args = []interface{}{userID, fetchLimit}
|
||||
} else {
|
||||
var cursorCreatedAt time.Time
|
||||
if err := s.pool.QueryRow(ctx, `SELECT created_at FROM chats WHERE id = $1`, cursor).Scan(&cursorCreatedAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil, ErrInvalidRequest
|
||||
}
|
||||
return nil, nil, fmt.Errorf("get cursor: %w", err)
|
||||
}
|
||||
query = `SELECT c.id, c.title, c.created_at FROM chats c
|
||||
INNER JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = $1 AND (c.created_at, c.id) > ($2, $3)
|
||||
ORDER BY c.created_at, c.id LIMIT $4`
|
||||
args = []interface{}{userID, cursorCreatedAt, cursor, fetchLimit}
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("query chats: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var chats []*model.Chat
|
||||
for rows.Next() {
|
||||
var chat model.Chat
|
||||
if err := rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt); err != nil {
|
||||
return nil, nil, fmt.Errorf("scan chat: %w", err)
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
chat.MemberIDs = []string{}
|
||||
chats = append(chats, &chat)
|
||||
}
|
||||
|
||||
if len(chats) > 0 {
|
||||
ids := make([]string, len(chats))
|
||||
for i, c := range chats {
|
||||
ids[i] = c.ID
|
||||
}
|
||||
mrows, err := s.pool.Query(ctx, `SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY($1::uuid[])`, ids)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("query members: %w", err)
|
||||
}
|
||||
defer mrows.Close()
|
||||
mm := make(map[string][]string)
|
||||
for mrows.Next() {
|
||||
var cid, mid string
|
||||
if err := mrows.Scan(&cid, &mid); err != nil {
|
||||
return nil, nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
mm[cid] = append(mm[cid], mid)
|
||||
}
|
||||
for _, c := range chats {
|
||||
if members, ok := mm[c.ID]; ok {
|
||||
c.MemberIDs = members
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var nextCursor *string
|
||||
if len(chats) > limit {
|
||||
chats = chats[:limit]
|
||||
lastID := chats[len(chats)-1].ID
|
||||
nextCursor = &lastID
|
||||
}
|
||||
if chats == nil {
|
||||
chats = []*model.Chat{}
|
||||
}
|
||||
return chats, nextCursor, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) AddMessage(ctx context.Context, chatID, senderID, text string) (*model.Message, error) {
|
||||
return s.insertMessage(ctx, chatID, senderID, text)
|
||||
}
|
||||
|
||||
func (s *PostgresStore) SendMessageIdempotent(ctx context.Context, chatID, senderID, text, idemKey, path, requestHash string) (*model.Message, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
scope := fmt.Sprintf("%s|%s|%s|%s", senderID, "POST", path, idemKey)
|
||||
lockID := int64(hashScope(scope))
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, lockID); err != nil {
|
||||
return nil, fmt.Errorf("advisory xact lock: %w", err)
|
||||
}
|
||||
|
||||
var existingHash string
|
||||
var existingBody []byte
|
||||
err = tx.QueryRow(ctx,
|
||||
`SELECT request_hash, response_body FROM idempotency_keys
|
||||
WHERE user_id = $1 AND method = $2 AND path = $3 AND key = $4`,
|
||||
senderID, "POST", path, idemKey).Scan(&existingHash, &existingBody)
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
if existingHash != requestHash {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
var msg model.Message
|
||||
if err := json.Unmarshal(existingBody, &msg); err != nil {
|
||||
return nil, fmt.Errorf("decode replay body: %w", err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return &msg, nil
|
||||
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
|
||||
msg, err := s.insertMessageTx(ctx, tx, chatID, senderID, text)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body, _ := json.Marshal(msg)
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, response_code, response_body)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
senderID, "POST", path, idemKey, requestHash, 201, body); err != nil {
|
||||
return nil, fmt.Errorf("insert idempotency key: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
return msg, nil
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("select idempotency key: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresStore) insertMessage(ctx context.Context, chatID, senderID, text string) (*model.Message, error) {
|
||||
var isMember bool
|
||||
if err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, senderID).Scan(&isMember); err != nil {
|
||||
return nil, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
if !isMember {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
var msg model.Message
|
||||
if err := s.pool.QueryRow(ctx,
|
||||
`INSERT INTO messages (chat_id, sender_id, text) VALUES ($1, $2, $3)
|
||||
RETURNING id, chat_id, sender_id, text, created_at`,
|
||||
chatID, senderID, text).
|
||||
Scan(&msg.ID, &msg.ChatID, &msg.SenderID, &msg.Text, &msg.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return &msg, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) insertMessageTx(ctx context.Context, tx pgx.Tx, chatID, senderID, text string) (*model.Message, error) {
|
||||
var isMember bool
|
||||
if err := tx.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, senderID).Scan(&isMember); err != nil {
|
||||
return nil, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
if !isMember {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
var msg model.Message
|
||||
if err := tx.QueryRow(ctx,
|
||||
`INSERT INTO messages (chat_id, sender_id, text) VALUES ($1, $2, $3)
|
||||
RETURNING id, chat_id, sender_id, text, created_at`,
|
||||
chatID, senderID, text).
|
||||
Scan(&msg.ID, &msg.ChatID, &msg.SenderID, &msg.Text, &msg.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return &msg, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetMessages(ctx context.Context, chatID, userID, cursor string, limit int) ([]*model.Message, *string, error) {
|
||||
var isMember bool
|
||||
if err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID).Scan(&isMember); err != nil {
|
||||
return nil, nil, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
if !isMember {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
|
||||
fetchLimit := limit + 1 // +1 для определения наличия下一页
|
||||
var query string
|
||||
var args []interface{}
|
||||
if cursor == "" {
|
||||
query = `SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = $1 ORDER BY created_at, id LIMIT $2`
|
||||
args = []interface{}{chatID, fetchLimit}
|
||||
} else {
|
||||
var cAt time.Time
|
||||
if err := s.pool.QueryRow(ctx, `SELECT created_at FROM messages WHERE id = $1 AND chat_id = $2`, cursor, chatID).Scan(&cAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil, ErrInvalidRequest
|
||||
}
|
||||
return nil, nil, fmt.Errorf("get cursor: %w", err)
|
||||
}
|
||||
query = `SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4`
|
||||
args = []interface{}{chatID, cAt, cursor, fetchLimit}
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("query messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var messages []*model.Message
|
||||
for rows.Next() {
|
||||
var msg model.Message
|
||||
if err := rows.Scan(&msg.ID, &msg.ChatID, &msg.SenderID, &msg.Text, &msg.CreatedAt); err != nil {
|
||||
return nil, nil, fmt.Errorf("scan message: %w", err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
messages = append(messages, &msg)
|
||||
}
|
||||
|
||||
// Ключевой фикс: история «заканчивается» ровно тогда, когда выбрали <= limit
|
||||
var nextCursor *string
|
||||
if len(messages) > limit {
|
||||
messages = messages[:limit]
|
||||
lastID := messages[len(messages)-1].ID
|
||||
nextCursor = &lastID
|
||||
}
|
||||
if messages == nil {
|
||||
messages = []*model.Message{}
|
||||
}
|
||||
return messages, nextCursor, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateSession(ctx context.Context, userID, tokenHash string, expiresAt time.Time) (*model.Session, error) {
|
||||
var session model.Session
|
||||
if err := s.pool.QueryRow(ctx,
|
||||
`INSERT INTO sessions (user_id, token_hash, expires_at) VALUES ($1, $2, $3)
|
||||
RETURNING id, user_id, token_hash, expires_at, created_at`,
|
||||
userID, tokenHash, expiresAt).
|
||||
Scan(&session.ID, &session.UserID, &session.TokenHash, &session.ExpiresAt, &session.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("insert session: %w", err)
|
||||
}
|
||||
session.ExpiresAt = session.ExpiresAt.UTC()
|
||||
session.CreatedAt = session.CreatedAt.UTC()
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetSession(ctx context.Context, tokenHash string) (*model.Session, error) {
|
||||
var session model.Session
|
||||
if err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, user_id, token_hash, expires_at, created_at FROM sessions WHERE token_hash = $1 AND expires_at > NOW()`,
|
||||
tokenHash).
|
||||
Scan(&session.ID, &session.UserID, &session.TokenHash, &session.ExpiresAt, &session.CreatedAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get session: %w", err)
|
||||
}
|
||||
session.ExpiresAt = session.ExpiresAt.UTC()
|
||||
session.CreatedAt = session.CreatedAt.UTC()
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) DeleteSession(ctx context.Context, tokenHash string) error {
|
||||
if _, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash = $1`, tokenHash); err != nil {
|
||||
return fmt.Errorf("delete session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hashScope(s string) uint32 {
|
||||
h := sha256.Sum256([]byte(s))
|
||||
return uint32(h[0])<<24 | uint32(h[1])<<16 | uint32(h[2])<<8 | uint32(h[3])
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
return err != nil && (contains(err.Error(), "23505") || contains(err.Error(), "duplicate key"))
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
for i := 0; i+len(substr) <= len(s); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var _ = hex.EncodeToString // подавление unused-импорта, если hex не нужен; удали строку и импорт hex, если компилятор ругается
|
||||
Reference in New Issue
Block a user