feat(lab2): PostgreSQL 18 persistence, Argon2id auth, Redis 7.4 sessions & cache, Grade 5 tracks
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonTime uint32 = 1
|
||||
argonMemory uint32 = 19 * 1024 // 19 MiB (OWASP interactive recommendation)
|
||||
argonThreads uint8 = 2
|
||||
argonKeyLen uint32 = 32
|
||||
argonSaltLen int = 16
|
||||
)
|
||||
|
||||
var dummyHash string
|
||||
|
||||
func init() {
|
||||
h, err := HashPassword("dummy-password-for-constant-time-check")
|
||||
if err == nil {
|
||||
dummyHash = h
|
||||
}
|
||||
}
|
||||
|
||||
// HashPassword hashes a UTF-8 password using Argon2id and returns a PHC-formatted string.
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("failed to generate salt: %w", err)
|
||||
}
|
||||
|
||||
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
|
||||
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
|
||||
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
|
||||
|
||||
encoded := fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonTime, argonThreads, b64Salt, b64Hash)
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
// VerifyPassword compares a UTF-8 password against an Argon2id PHC string in constant time.
|
||||
func VerifyPassword(password, encodedHash string) (bool, error) {
|
||||
parts := strings.Split(encodedHash, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false, errors.New("invalid argon2id hash format")
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var memory, timeCost uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &timeCost, &threads); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
expectedHash, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
computedHash := argon2.IDKey([]byte(password), salt, timeCost, memory, threads, uint32(len(expectedHash)))
|
||||
if subtle.ConstantTimeCompare(computedHash, expectedHash) == 1 {
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// VerifyDummy runs an Argon2id verification against a dummy hash to prevent timing attacks on unknown usernames.
|
||||
func VerifyDummy(password string) {
|
||||
if dummyHash != "" {
|
||||
_, _ = VerifyPassword(password, dummyHash)
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateSessionToken generates an opaque 256-bit (32-byte) random token encoded as 64 hex chars,
|
||||
// along with its SHA-256 hex digest for storage.
|
||||
func GenerateSessionToken() (rawToken string, tokenHash string, err error) {
|
||||
buf := make([]byte, 32) // 256 bits of entropy
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", "", fmt.Errorf("failed to generate random token: %w", err)
|
||||
}
|
||||
rawToken = hex.EncodeToString(buf)
|
||||
tokenHash = HashToken(rawToken)
|
||||
return rawToken, tokenHash, nil
|
||||
}
|
||||
|
||||
// HashToken returns the lowercase SHA-256 hex digest of an opaque session token.
|
||||
func HashToken(rawToken string) string {
|
||||
sum := sha256.Sum256([]byte(rawToken))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHashAndVerifyPassword(t *testing.T) {
|
||||
pw := "Сложный:Пароль:С:Двоеточиями:2026!🚀"
|
||||
hash, err := HashPassword(pw)
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword failed: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(hash, "$argon2id$v=19$") {
|
||||
t.Fatalf("expected Argon2id PHC prefix, got: %s", hash)
|
||||
}
|
||||
|
||||
ok, err := VerifyPassword(pw, hash)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("expected password verification to succeed, err=%v, ok=%v", err, ok)
|
||||
}
|
||||
|
||||
okWrong, err := VerifyPassword("WrongPassword-12345!", hash)
|
||||
if err != nil || okWrong {
|
||||
t.Fatalf("expected wrong password to fail verification")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateSessionToken(t *testing.T) {
|
||||
raw, hash, err := GenerateSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSessionToken failed: %v", err)
|
||||
}
|
||||
if len(raw) != 64 {
|
||||
t.Fatalf("expected 64-char hex raw token (256-bit), got len=%d", len(raw))
|
||||
}
|
||||
if len(hash) != 64 {
|
||||
t.Fatalf("expected 64-char SHA-256 hex digest, got len=%d", len(hash))
|
||||
}
|
||||
if HashToken(raw) != hash {
|
||||
t.Fatalf("HashToken mismatch")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"messenger/internal/model"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
//go:embed openapi.json
|
||||
var openAPISpec []byte
|
||||
|
||||
const swaggerUIHTML = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>MTUCI Messenger API (Lab 2) - Swagger UI</title>
|
||||
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" />
|
||||
<style>
|
||||
body { margin: 0; background: #fafafa; }
|
||||
.swagger-ui .topbar { display: none; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="swagger-ui"></div>
|
||||
<script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
|
||||
<script>
|
||||
window.onload = function() {
|
||||
SwaggerUIBundle({
|
||||
url: "/openapi.json",
|
||||
dom_id: '#swagger-ui',
|
||||
deepLinking: true,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIBundle.SwaggerUIStandalonePreset
|
||||
],
|
||||
layout: "BaseLayout"
|
||||
});
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
type APIHandler struct {
|
||||
store store.Store
|
||||
sessionTTL int
|
||||
}
|
||||
|
||||
func NewAPIHandler(st store.Store, sessionTTL int) *APIHandler {
|
||||
if sessionTTL <= 0 {
|
||||
sessionTTL = 3600
|
||||
}
|
||||
return &APIHandler{
|
||||
store: st,
|
||||
sessionTTL: sessionTTL,
|
||||
}
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, dst interface{}) error {
|
||||
if r.Body == nil {
|
||||
return errors.New("request body is missing")
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return errors.New("request body is empty")
|
||||
}
|
||||
var unmarshalTypeError *json.UnmarshalTypeError
|
||||
if errors.As(err, &unmarshalTypeError) {
|
||||
return fmt.Errorf("field '%s' has incorrect type (expected %s)", unmarshalTypeError.Field, unmarshalTypeError.Type)
|
||||
}
|
||||
return fmt.Errorf("malformed JSON or unexpected field: %v", err)
|
||||
}
|
||||
|
||||
if dec.More() {
|
||||
return errors.New("request body contains multiple JSON values")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeStoreError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrConflict):
|
||||
WriteError(w, r, http.StatusConflict, "conflict", "resource conflict")
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
WriteError(w, r, http.StatusNotFound, "not_found", "resource not found or access denied")
|
||||
case errors.Is(err, store.ErrUnauthorized):
|
||||
WriteBearerUnauthorized(w, r, "unauthorized")
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
|
||||
case errors.Is(err, store.ErrBadRequest):
|
||||
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
default:
|
||||
WriteError(w, r, http.StatusInternalServerError, "internal_error", "internal server error")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleLiveness(w http.ResponseWriter, r *http.Request) {
|
||||
WriteJSON(w, r, http.StatusOK, model.HealthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleReadiness(w http.ResponseWriter, r *http.Request) {
|
||||
if err := h.store.Ready(r.Context()); err != nil {
|
||||
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "database dependency is not ready")
|
||||
return
|
||||
}
|
||||
WriteJSON(w, r, http.StatusOK, model.HealthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleRegisterUser(w http.ResponseWriter, r *http.Request) {
|
||||
var req model.CreateUserRequest
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.store.CreateUser(r.Context(), req)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, r, http.StatusCreated, user)
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleCreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
// Contract: POST /auth/sessions accepts ONLY Authorization: Basic <base64(username:password)>, without JSON body.
|
||||
if r.Body != nil {
|
||||
defer r.Body.Close()
|
||||
var buf [1]byte
|
||||
n, _ := r.Body.Read(buf[:])
|
||||
if n > 0 {
|
||||
WriteError(w, r, http.StatusBadRequest, "invalid_request", "POST /api/v1/auth/sessions must not include a request body")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||
if authHeader == "" {
|
||||
WriteBasicUnauthorized(w, r, "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Basic") {
|
||||
WriteBasicUnauthorized(w, r, "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
b64Payload := strings.TrimSpace(parts[1])
|
||||
decoded, err := base64.StdEncoding.DecodeString(b64Payload)
|
||||
if err != nil || !utf8.Valid(decoded) {
|
||||
WriteBasicUnauthorized(w, r, "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
credParts := strings.SplitN(string(decoded), ":", 2)
|
||||
if len(credParts) != 2 {
|
||||
WriteBasicUnauthorized(w, r, "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
username := credParts[0]
|
||||
password := credParts[1]
|
||||
|
||||
sess, err := h.store.AuthenticateAndCreateSession(r.Context(), username, password, h.sessionTTL)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
|
||||
return
|
||||
}
|
||||
WriteBasicUnauthorized(w, r, "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, r, http.StatusCreated, sess)
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleRevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
rawToken := GetAuthToken(r.Context())
|
||||
if rawToken == "" {
|
||||
WriteBearerUnauthorized(w, r, "unauthenticated")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.store.RevokeSession(r.Context(), rawToken); err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
|
||||
return
|
||||
}
|
||||
WriteBearerUnauthorized(w, r, "session already revoked or expired")
|
||||
return
|
||||
}
|
||||
|
||||
reqID := GetRequestID(r.Context())
|
||||
w.Header().Set("X-Request-Id", reqID)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleCurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
user := GetAuthUser(r.Context())
|
||||
if user == nil {
|
||||
WriteBearerUnauthorized(w, r, "unauthenticated")
|
||||
return
|
||||
}
|
||||
WriteJSON(w, r, http.StatusOK, user)
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleCreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
caller := GetAuthUser(r.Context())
|
||||
if caller == nil {
|
||||
WriteBearerUnauthorized(w, r, "unauthenticated")
|
||||
return
|
||||
}
|
||||
|
||||
var req model.CreateChatRequest
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.CreateChat(r.Context(), caller.ID, req)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, r, http.StatusCreated, chat)
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleListChats(w http.ResponseWriter, r *http.Request) {
|
||||
caller := GetAuthUser(r.Context())
|
||||
if caller == nil {
|
||||
WriteBearerUnauthorized(w, r, "unauthenticated")
|
||||
return
|
||||
}
|
||||
|
||||
limit := 50
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
if limitStr != "" {
|
||||
l, err := strconv.Atoi(limitStr)
|
||||
if err != nil || l < 1 || l > 100 {
|
||||
WriteError(w, r, http.StatusBadRequest, "invalid_request", "limit must be an integer between 1 and 100")
|
||||
return
|
||||
}
|
||||
limit = l
|
||||
}
|
||||
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
page, err := h.store.ListChats(r.Context(), caller.ID, limit, cursor)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleGetChat(w http.ResponseWriter, r *http.Request) {
|
||||
caller := GetAuthUser(r.Context())
|
||||
if caller == nil {
|
||||
WriteBearerUnauthorized(w, r, "unauthenticated")
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id UUID")
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.GetChat(r.Context(), caller.ID, chatID)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, r, http.StatusOK, chat)
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
caller := GetAuthUser(r.Context())
|
||||
if caller == nil {
|
||||
WriteBearerUnauthorized(w, r, "unauthenticated")
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id UUID")
|
||||
return
|
||||
}
|
||||
|
||||
var req model.CreateMessageRequest
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
msg, err := h.store.CreateMessage(r.Context(), caller.ID, chatID, req)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, r, http.StatusCreated, msg)
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
caller := GetAuthUser(r.Context())
|
||||
if caller == nil {
|
||||
WriteBearerUnauthorized(w, r, "unauthenticated")
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id UUID")
|
||||
return
|
||||
}
|
||||
|
||||
limit := 50
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
if limitStr != "" {
|
||||
l, err := strconv.Atoi(limitStr)
|
||||
if err != nil || l < 1 || l > 100 {
|
||||
WriteError(w, r, http.StatusBadRequest, "invalid_request", "limit must be an integer between 1 and 100")
|
||||
return
|
||||
}
|
||||
limit = l
|
||||
}
|
||||
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
page, err := h.store.ListMessages(r.Context(), caller.ID, chatID, limit, cursor)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleInternalStats(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("reset") == "1" {
|
||||
h.store.ResetStats()
|
||||
}
|
||||
if mode := r.URL.Query().Get("mode"); mode != "" {
|
||||
h.store.SetCacheMode(mode)
|
||||
}
|
||||
WriteJSON(w, r, http.StatusOK, h.store.Stats(r.Context()))
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleOpenAPISpec(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("X-Request-Id", GetRequestID(r.Context()))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(openAPISpec)
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleSwaggerUI(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("X-Request-Id", GetRequestID(r.Context()))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(swaggerUIHTML))
|
||||
}
|
||||
|
||||
func (h *APIHandler) HandleNotFound(w http.ResponseWriter, r *http.Request) {
|
||||
WriteError(w, r, http.StatusNotFound, "not_found", fmt.Sprintf("route %s %s not found", r.Method, r.URL.Path))
|
||||
}
|
||||
|
||||
func RegisterRoutes(st store.Store, sessionTTL int) http.Handler {
|
||||
api := NewAPIHandler(st, sessionTTL)
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// Documentation & schema
|
||||
mux.HandleFunc("GET /docs", api.HandleSwaggerUI)
|
||||
mux.HandleFunc("GET /docs/", api.HandleSwaggerUI)
|
||||
mux.HandleFunc("GET /openapi.json", api.HandleOpenAPISpec)
|
||||
|
||||
// Internal diagnostics for Grade 5 cache & SQL experiments
|
||||
mux.HandleFunc("GET /internal/stats", api.HandleInternalStats)
|
||||
mux.HandleFunc("POST /internal/stats", api.HandleInternalStats)
|
||||
|
||||
// Public routes
|
||||
mux.HandleFunc("GET /health/live", api.HandleLiveness)
|
||||
mux.HandleFunc("GET /health/ready", api.HandleReadiness)
|
||||
mux.HandleFunc("POST /api/v1/users", api.HandleRegisterUser)
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", api.HandleCreateSession)
|
||||
|
||||
// Protected Bearer routes
|
||||
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", RequireBearerAuth(st, api.HandleRevokeSession))
|
||||
mux.HandleFunc("GET /api/v1/users/me", RequireBearerAuth(st, api.HandleCurrentUser))
|
||||
mux.HandleFunc("POST /api/v1/chats", RequireBearerAuth(st, api.HandleCreateChat))
|
||||
mux.HandleFunc("GET /api/v1/chats", RequireBearerAuth(st, api.HandleListChats))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", RequireBearerAuth(st, api.HandleGetChat))
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", RequireBearerAuth(st, api.HandleCreateMessage))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", RequireBearerAuth(st, api.HandleListMessages))
|
||||
|
||||
// Fallback 404 handler
|
||||
mux.HandleFunc("/", api.HandleNotFound)
|
||||
|
||||
var handler http.Handler = mux
|
||||
handler = LoggingMiddleware(handler)
|
||||
handler = RequestIDMiddleware(handler)
|
||||
|
||||
return handler
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"messenger/internal/model"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const (
|
||||
requestIDContextKey contextKey = "request_id"
|
||||
userContextKey contextKey = "user"
|
||||
tokenContextKey contextKey = "token"
|
||||
)
|
||||
|
||||
type loggingResponseWriter struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (lrw *loggingResponseWriter) WriteHeader(code int) {
|
||||
lrw.statusCode = code
|
||||
lrw.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func RequestIDMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := strings.TrimSpace(r.Header.Get("X-Request-Id"))
|
||||
if reqID == "" {
|
||||
reqID = uuid.New().String()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", reqID)
|
||||
ctx := context.WithValue(r.Context(), requestIDContextKey, reqID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func LoggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
lrw := &loggingResponseWriter{ResponseWriter: w, statusCode: http.StatusOK}
|
||||
|
||||
next.ServeHTTP(lrw, r)
|
||||
|
||||
reqID, _ := r.Context().Value(requestIDContextKey).(string)
|
||||
duration := time.Since(start)
|
||||
|
||||
logEntry := map[string]interface{}{
|
||||
"time": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
"method": r.Method,
|
||||
"path": r.URL.Path,
|
||||
"status": lrw.statusCode,
|
||||
"duration_ms": float64(duration.Microseconds()) / 1000.0,
|
||||
"request_id": reqID,
|
||||
"remote_ip": r.RemoteAddr,
|
||||
}
|
||||
logBytes, _ := json.Marshal(logEntry)
|
||||
fmt.Fprintln(os.Stdout, string(logBytes))
|
||||
})
|
||||
}
|
||||
|
||||
func GetRequestID(ctx context.Context) string {
|
||||
if val, ok := ctx.Value(requestIDContextKey).(string); ok && val != "" {
|
||||
return val
|
||||
}
|
||||
return uuid.New().String()
|
||||
}
|
||||
|
||||
func WriteError(w http.ResponseWriter, r *http.Request, status int, code, message string) {
|
||||
reqID := GetRequestID(r.Context())
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Request-Id", reqID)
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(model.ErrorResponse{
|
||||
Error: model.ErrorDetail{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: reqID,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func WriteBasicUnauthorized(w http.ResponseWriter, r *http.Request, message string) {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
WriteError(w, r, http.StatusUnauthorized, "unauthorized", message)
|
||||
}
|
||||
|
||||
func WriteBearerUnauthorized(w http.ResponseWriter, r *http.Request, message string) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
WriteError(w, r, http.StatusUnauthorized, "unauthorized", message)
|
||||
}
|
||||
|
||||
func WriteJSON(w http.ResponseWriter, r *http.Request, status int, data interface{}) {
|
||||
reqID := GetRequestID(r.Context())
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Request-Id", reqID)
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func RequireBearerAuth(st store.Store, next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// Note: X-User-Id is intentionally ignored in Lab 2+ per contract.
|
||||
authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||
if authHeader == "" {
|
||||
WriteBearerUnauthorized(w, r, "missing Authorization header")
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
WriteBearerUnauthorized(w, r, "Bearer authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
rawToken := strings.TrimSpace(parts[1])
|
||||
if rawToken == "" || strings.ContainsAny(rawToken, " \t\r\n") {
|
||||
WriteBearerUnauthorized(w, r, "invalid Bearer token")
|
||||
return
|
||||
}
|
||||
|
||||
user, err := st.GetUserByToken(r.Context(), rawToken)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
|
||||
return
|
||||
}
|
||||
WriteBearerUnauthorized(w, r, "invalid, expired, or revoked session token")
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), userContextKey, user)
|
||||
ctx = context.WithValue(ctx, tokenContextKey, rawToken)
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
func GetAuthUser(ctx context.Context) *model.User {
|
||||
if user, ok := ctx.Value(userContextKey).(*model.User); ok {
|
||||
return user
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetAuthToken(ctx context.Context) string {
|
||||
if tok, ok := ctx.Value(tokenContextKey).(string); ok {
|
||||
return tok
|
||||
}
|
||||
return ""
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,75 @@
|
||||
package model
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type Message 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 CreateMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type ChatPage struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type MessagePage struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type ErrorDetail struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error ErrorDetail `json:"error"`
|
||||
}
|
||||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type CursorData struct {
|
||||
Scope string `json:"s"`
|
||||
Time string `json:"t"`
|
||||
ID string `json:"i"`
|
||||
}
|
||||
@@ -0,0 +1,888 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"messenger/internal/auth"
|
||||
"messenger/internal/model"
|
||||
)
|
||||
|
||||
type cachedSession struct {
|
||||
User model.User `json:"user"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
type PostgresStore struct {
|
||||
pool *pgxpool.Pool
|
||||
rdb *redis.Client
|
||||
queryTimeout time.Duration
|
||||
|
||||
sfGroup singleflight.Group
|
||||
|
||||
mu sync.RWMutex
|
||||
cacheMode string
|
||||
|
||||
sqlQueries atomic.Int64
|
||||
cacheHits atomic.Int64
|
||||
cacheMisses atomic.Int64
|
||||
singleflightShared atomic.Int64
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
MaxConns int32
|
||||
MinConns int32
|
||||
QueryTimeout time.Duration
|
||||
CacheMode string
|
||||
}
|
||||
|
||||
func NewPostgresStore(ctx context.Context, cfg Config) (*PostgresStore, error) {
|
||||
poolCfg, err := pgxpool.ParseConfig(cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid database URL: %w", err)
|
||||
}
|
||||
|
||||
if cfg.MaxConns <= 0 {
|
||||
cfg.MaxConns = 25
|
||||
}
|
||||
if cfg.MinConns <= 0 {
|
||||
cfg.MinConns = 4
|
||||
}
|
||||
if cfg.QueryTimeout <= 0 {
|
||||
cfg.QueryTimeout = 5 * time.Second
|
||||
}
|
||||
if cfg.CacheMode == "" {
|
||||
cfg.CacheMode = "write_through_versioned"
|
||||
}
|
||||
|
||||
poolCfg.MaxConns = cfg.MaxConns
|
||||
poolCfg.MinConns = cfg.MinConns
|
||||
poolCfg.MaxConnLifetime = 30 * time.Minute
|
||||
poolCfg.MaxConnIdleTime = 5 * time.Minute
|
||||
poolCfg.HealthCheckPeriod = 15 * time.Second
|
||||
poolCfg.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create pgx pool: %w", err)
|
||||
}
|
||||
|
||||
var rdb *redis.Client
|
||||
if cfg.CacheURL != "" {
|
||||
opt, err := redis.ParseURL(cfg.CacheURL)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("invalid cache URL: %w", err)
|
||||
}
|
||||
opt.DialTimeout = 500 * time.Millisecond
|
||||
opt.ReadTimeout = 500 * time.Millisecond
|
||||
opt.WriteTimeout = 500 * time.Millisecond
|
||||
opt.PoolSize = 30
|
||||
opt.MaxRetries = 1
|
||||
rdb = redis.NewClient(opt)
|
||||
}
|
||||
|
||||
return &PostgresStore{
|
||||
pool: pool,
|
||||
rdb: rdb,
|
||||
queryTimeout: cfg.QueryTimeout,
|
||||
cacheMode: cfg.CacheMode,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) RunMigrations(ctx context.Context, version string, sqlContent string) error {
|
||||
qCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(qCtx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin migration tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(qCtx) }()
|
||||
|
||||
_, err = tx.Exec(qCtx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(64) PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create schema_migrations: %w", err)
|
||||
}
|
||||
|
||||
var alreadyApplied bool
|
||||
err = tx.QueryRow(qCtx, `SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = $1)`, version).Scan(&alreadyApplied)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check migration version: %w", err)
|
||||
}
|
||||
|
||||
if !alreadyApplied {
|
||||
if _, err := tx.Exec(qCtx, sqlContent); err != nil {
|
||||
return fmt.Errorf("apply migration %s: %w", version, err)
|
||||
}
|
||||
if _, err := tx.Exec(qCtx, `INSERT INTO schema_migrations (version, applied_at) VALUES ($1, NOW())`, version); err != nil {
|
||||
return fmt.Errorf("record migration %s: %w", version, err)
|
||||
}
|
||||
log.Printf("Migration %s applied successfully", version)
|
||||
} else {
|
||||
log.Printf("Migration %s already applied (idempotent skip)", version)
|
||||
}
|
||||
|
||||
return tx.Commit(qCtx)
|
||||
}
|
||||
|
||||
func (s *PostgresStore) Ready(ctx context.Context) error {
|
||||
qCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
var ok int
|
||||
if err := s.pool.QueryRow(qCtx, `SELECT 1 FROM schema_migrations LIMIT 1`).Scan(&ok); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) Close() {
|
||||
if s.rdb != nil {
|
||||
_ = s.rdb.Close()
|
||||
}
|
||||
if s.pool != nil {
|
||||
s.pool.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresStore) getCacheMode() string {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.cacheMode
|
||||
}
|
||||
|
||||
func (s *PostgresStore) SetCacheMode(mode string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.cacheMode = mode
|
||||
}
|
||||
|
||||
func (s *PostgresStore) ResetStats() {
|
||||
s.sqlQueries.Store(0)
|
||||
s.cacheHits.Store(0)
|
||||
s.cacheMisses.Store(0)
|
||||
s.singleflightShared.Store(0)
|
||||
}
|
||||
|
||||
func (s *PostgresStore) Stats(ctx context.Context) StoreStats {
|
||||
redisOK := false
|
||||
if s.rdb != nil {
|
||||
rCtx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := s.rdb.Ping(rCtx).Err(); err == nil {
|
||||
redisOK = true
|
||||
}
|
||||
}
|
||||
return StoreStats{
|
||||
SQLQueries: s.sqlQueries.Load(),
|
||||
CacheHits: s.cacheHits.Load(),
|
||||
CacheMisses: s.cacheMisses.Load(),
|
||||
SingleflightShared: s.singleflightShared.Load(),
|
||||
CacheMode: s.getCacheMode(),
|
||||
RedisConnected: redisOK,
|
||||
}
|
||||
}
|
||||
|
||||
func classifyDBError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "23505": // unique_violation
|
||||
return fmt.Errorf("%w: resource already exists", ErrConflict)
|
||||
case "23503": // foreign_key_violation
|
||||
return fmt.Errorf("%w: referenced entity does not exist", ErrBadRequest)
|
||||
case "23514": // check_violation
|
||||
return fmt.Errorf("%w: check constraint failed", ErrBadRequest)
|
||||
case "22P02": // invalid_text_representation (e.g. bad UUID)
|
||||
return fmt.Errorf("%w: invalid identifier format", ErrBadRequest)
|
||||
}
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return fmt.Errorf("%w: database operation failed", ErrUnavailable)
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateUser(ctx context.Context, req model.CreateUserRequest) (*model.User, error) {
|
||||
if !usernameRegex.MatchString(req.Username) {
|
||||
return nil, fmt.Errorf("%w: username must match ^[a-z0-9_]{3,32}$", ErrBadRequest)
|
||||
}
|
||||
dnLen := utf8.RuneCountInString(req.DisplayName)
|
||||
if dnLen < 1 || dnLen > 100 || strings.TrimSpace(req.DisplayName) == "" {
|
||||
return nil, fmt.Errorf("%w: display_name must be 1..100 characters and not only whitespace", ErrBadRequest)
|
||||
}
|
||||
pwLen := utf8.RuneCountInString(req.Password)
|
||||
if pwLen < 12 || pwLen > 128 || strings.TrimSpace(req.Password) == "" {
|
||||
return nil, fmt.Errorf("%w: password must be 12..128 characters and not only whitespace", ErrBadRequest)
|
||||
}
|
||||
|
||||
pwHash, err := auth.HashPassword(req.Password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: failed to hash password", ErrUnavailable)
|
||||
}
|
||||
|
||||
qCtx, cancel := context.WithTimeout(ctx, s.queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
id := uuid.New().String()
|
||||
now := NowUTC()
|
||||
|
||||
s.sqlQueries.Add(1)
|
||||
_, err = s.pool.Exec(qCtx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5::timestamptz)
|
||||
`, id, req.Username, req.DisplayName, pwHash, now)
|
||||
if err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
return &model.User{
|
||||
ID: id,
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
CreatedAt: FormatTime(now),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) AuthenticateAndCreateSession(ctx context.Context, username, password string, ttlSeconds int) (*model.Session, error) {
|
||||
if !usernameRegex.MatchString(username) {
|
||||
auth.VerifyDummy(password)
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
pwLen := utf8.RuneCountInString(password)
|
||||
if pwLen < 1 || pwLen > 256 {
|
||||
auth.VerifyDummy(password)
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
qCtx, cancel := context.WithTimeout(ctx, s.queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
var user model.User
|
||||
var pwHash string
|
||||
var createdAt time.Time
|
||||
|
||||
s.sqlQueries.Add(1)
|
||||
err := s.pool.QueryRow(qCtx, `
|
||||
SELECT id::text, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`, username).Scan(&user.ID, &user.Username, &user.DisplayName, &pwHash, &createdAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
auth.VerifyDummy(password)
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
user.CreatedAt = FormatTime(createdAt)
|
||||
|
||||
valid, err := auth.VerifyPassword(password, pwHash)
|
||||
if err != nil || !valid {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
rawToken, tokenHash, err := auth.GenerateSessionToken()
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
|
||||
if ttlSeconds <= 0 {
|
||||
ttlSeconds = 3600
|
||||
}
|
||||
now := NowUTC()
|
||||
expiresAt := now.Add(time.Duration(ttlSeconds) * time.Second)
|
||||
|
||||
s.sqlQueries.Add(1)
|
||||
_, err = s.pool.Exec(qCtx, `
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at, created_at)
|
||||
VALUES ($1, $2::uuid, $3::timestamptz, $4::timestamptz)
|
||||
`, tokenHash, user.ID, expiresAt, now)
|
||||
if err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
s.cacheSession(ctx, tokenHash, user, expiresAt)
|
||||
|
||||
return &model.Session{
|
||||
Token: rawToken,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: FormatTime(expiresAt),
|
||||
User: user,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) cacheSession(ctx context.Context, tokenHash string, user model.User, expiresAt time.Time) {
|
||||
if s.rdb == nil {
|
||||
return
|
||||
}
|
||||
remaining := time.Until(expiresAt)
|
||||
if remaining <= 0 {
|
||||
return
|
||||
}
|
||||
payload, err := json.Marshal(cachedSession{
|
||||
User: user,
|
||||
ExpiresAt: expiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rCtx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
key := "sess:" + tokenHash
|
||||
if err := s.rdb.Set(rCtx, key, payload, remaining).Err(); err != nil {
|
||||
log.Printf("WARN: redis session write failed (graceful bypass): %v", err)
|
||||
return
|
||||
}
|
||||
_ = s.rdb.ExpireAt(rCtx, key, expiresAt).Err()
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetUserByToken(ctx context.Context, rawToken string) (*model.User, error) {
|
||||
if len(rawToken) < 32 || len(rawToken) > 256 {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
tokenHash := auth.HashToken(rawToken)
|
||||
now := NowUTC()
|
||||
|
||||
// 1. Check Valkey/Redis session cache first
|
||||
if s.rdb != nil {
|
||||
rCtx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
val, err := s.rdb.Get(rCtx, "sess:"+tokenHash).Bytes()
|
||||
cancel()
|
||||
if err == nil {
|
||||
var cs cachedSession
|
||||
if jsonErr := json.Unmarshal(val, &cs); jsonErr == nil {
|
||||
if now.Before(cs.ExpiresAt) {
|
||||
s.cacheHits.Add(1)
|
||||
return &cs.User, nil
|
||||
}
|
||||
}
|
||||
} else if !errors.Is(err, redis.Nil) {
|
||||
log.Printf("WARN: redis session read failed (falling back to PostgreSQL): %v", err)
|
||||
}
|
||||
s.cacheMisses.Add(1)
|
||||
}
|
||||
|
||||
// 2. Fallback to PostgreSQL source of truth
|
||||
qCtx, cancel := context.WithTimeout(ctx, s.queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
var user model.User
|
||||
var userCreatedAt, expiresAt time.Time
|
||||
|
||||
s.sqlQueries.Add(1)
|
||||
err := s.pool.QueryRow(qCtx, `
|
||||
SELECT u.id::text, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1
|
||||
`, tokenHash).Scan(&user.ID, &user.Username, &user.DisplayName, &userCreatedAt, &expiresAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
expiresAt = expiresAt.UTC().Truncate(time.Microsecond)
|
||||
if !now.Before(expiresAt) {
|
||||
// Session expired: clean up lazily and reject
|
||||
_, _ = s.pool.Exec(qCtx, `DELETE FROM sessions WHERE token_hash = $1`, tokenHash)
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
user.CreatedAt = FormatTime(userCreatedAt)
|
||||
// Repopulate Valkey/Redis with original expires_at (never extending TTL!)
|
||||
s.cacheSession(ctx, tokenHash, user, expiresAt)
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) RevokeSession(ctx context.Context, rawToken string) error {
|
||||
if len(rawToken) < 32 || len(rawToken) > 256 {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
tokenHash := auth.HashToken(rawToken)
|
||||
|
||||
if s.rdb != nil {
|
||||
rCtx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
if err := s.rdb.Del(rCtx, "sess:"+tokenHash).Err(); err != nil {
|
||||
log.Printf("WARN: redis session delete failed: %v", err)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
|
||||
qCtx, cancel := context.WithTimeout(ctx, s.queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
s.sqlQueries.Add(1)
|
||||
tag, err := s.pool.Exec(qCtx, `
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1 AND expires_at > $2::timestamptz
|
||||
`, tokenHash, NowUTC())
|
||||
if err != nil {
|
||||
return classifyDBError(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateChat(ctx context.Context, callerID string, req model.CreateChatRequest) (*model.Chat, error) {
|
||||
titleLen := utf8.RuneCountInString(req.Title)
|
||||
if titleLen < 1 || titleLen > 100 || strings.TrimSpace(req.Title) == "" {
|
||||
return nil, fmt.Errorf("%w: title must be 1..100 characters and not only whitespace", ErrBadRequest)
|
||||
}
|
||||
if len(req.MemberIDs) < 1 || len(req.MemberIDs) > 100 {
|
||||
return nil, fmt.Errorf("%w: member_ids must contain 1..100 items", ErrBadRequest)
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(req.MemberIDs))
|
||||
callerIncluded := false
|
||||
for _, mid := range req.MemberIDs {
|
||||
if _, err := uuid.Parse(mid); err != nil {
|
||||
return nil, fmt.Errorf("%w: invalid UUID in member_ids", ErrBadRequest)
|
||||
}
|
||||
if _, exists := seen[mid]; exists {
|
||||
return nil, fmt.Errorf("%w: duplicate user in member_ids", ErrBadRequest)
|
||||
}
|
||||
seen[mid] = struct{}{}
|
||||
if mid == callerID {
|
||||
callerIncluded = true
|
||||
}
|
||||
}
|
||||
if !callerIncluded {
|
||||
return nil, fmt.Errorf("%w: caller must be included in member_ids", ErrBadRequest)
|
||||
}
|
||||
|
||||
qCtx, cancel := context.WithTimeout(ctx, s.queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
// Composite atomic transaction: insert chat + insert all chat_members
|
||||
tx, err := s.pool.Begin(qCtx)
|
||||
if err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(qCtx) }()
|
||||
|
||||
chatID := uuid.New().String()
|
||||
now := NowUTC()
|
||||
|
||||
s.sqlQueries.Add(1)
|
||||
_, err = tx.Exec(qCtx, `
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
VALUES ($1::uuid, $2, $3::timestamptz)
|
||||
`, chatID, req.Title, now)
|
||||
if err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
for idx, mid := range req.MemberIDs {
|
||||
s.sqlQueries.Add(1)
|
||||
_, err = tx.Exec(qCtx, `
|
||||
INSERT INTO chat_members (chat_id, user_id, ord)
|
||||
VALUES ($1::uuid, $2::uuid, $3)
|
||||
`, chatID, mid, idx)
|
||||
if err != nil {
|
||||
// If any member does not exist in users, FK constraint 23503 triggers and rolls back the entire chat creation!
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(qCtx); err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
membersCopy := make([]string, len(req.MemberIDs))
|
||||
copy(membersCopy, req.MemberIDs)
|
||||
|
||||
return &model.Chat{
|
||||
ID: chatID,
|
||||
Title: req.Title,
|
||||
MemberIDs: membersCopy,
|
||||
CreatedAt: FormatTime(now),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) ListChats(ctx context.Context, callerID string, limit int, cursorStr string) (*model.ChatPage, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, fmt.Errorf("%w: limit must be between 1 and 100", ErrBadRequest)
|
||||
}
|
||||
|
||||
scope := "chats:" + callerID
|
||||
var hasCursor bool
|
||||
var cursorTime time.Time
|
||||
var cursorID string
|
||||
if cursorStr != "" {
|
||||
var err error
|
||||
cursorTime, cursorID, err = DecodeCursor(cursorStr, scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hasCursor = true
|
||||
}
|
||||
|
||||
qCtx, cancel := context.WithTimeout(ctx, s.queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
var rows pgx.Rows
|
||||
var err error
|
||||
s.sqlQueries.Add(1)
|
||||
if !hasCursor {
|
||||
rows, err = s.pool.Query(qCtx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
array_agg(cm_all.user_id::text ORDER BY cm_all.ord ASC) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm_me ON cm_me.chat_id = c.id AND cm_me.user_id = $1::uuid
|
||||
JOIN chat_members cm_all ON cm_all.chat_id = c.id
|
||||
GROUP BY c.id, c.title, c.created_at
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
LIMIT $2
|
||||
`, callerID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(qCtx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
array_agg(cm_all.user_id::text ORDER BY cm_all.ord ASC) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm_me ON cm_me.chat_id = c.id AND cm_me.user_id = $1::uuid
|
||||
JOIN chat_members cm_all ON cm_all.chat_id = c.id
|
||||
WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
|
||||
GROUP BY c.id, c.title, c.created_at
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
LIMIT $4
|
||||
`, callerID, cursorTime, cursorID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]model.Chat, 0, limit)
|
||||
for rows.Next() {
|
||||
var ch model.Chat
|
||||
var createdAt time.Time
|
||||
if err := rows.Scan(&ch.ID, &ch.Title, &createdAt, &ch.MemberIDs); err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
ch.CreatedAt = FormatTime(createdAt)
|
||||
items = append(items, ch)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
var nextCursor *string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
c := EncodeCursor(scope, last.CreatedAt, last.ID)
|
||||
nextCursor = &c
|
||||
}
|
||||
|
||||
return &model.ChatPage{
|
||||
Items: items,
|
||||
NextCursor: nextCursor,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetChat(ctx context.Context, callerID, chatID string) (*model.Chat, error) {
|
||||
qCtx, cancel := context.WithTimeout(ctx, s.queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
var ch model.Chat
|
||||
var createdAt time.Time
|
||||
|
||||
s.sqlQueries.Add(1)
|
||||
err := s.pool.QueryRow(qCtx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
array_agg(cm.user_id::text ORDER BY cm.ord ASC) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1::uuid
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = c.id AND user_id = $2::uuid
|
||||
)
|
||||
GROUP BY c.id, c.title, c.created_at
|
||||
`, chatID, callerID).Scan(&ch.ID, &ch.Title, &createdAt, &ch.MemberIDs)
|
||||
if err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
ch.CreatedAt = FormatTime(createdAt)
|
||||
return &ch, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateMessage(ctx context.Context, callerID, chatID string, req model.CreateMessageRequest) (*model.Message, error) {
|
||||
textLen := utf8.RuneCountInString(req.Text)
|
||||
if textLen < 1 || textLen > 4000 || strings.TrimSpace(req.Text) == "" {
|
||||
return nil, fmt.Errorf("%w: text must be 1..4000 characters and not only whitespace", ErrBadRequest)
|
||||
}
|
||||
|
||||
qCtx, cancel := context.WithTimeout(ctx, s.queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
msgID := uuid.New().String()
|
||||
now := NowUTC()
|
||||
|
||||
s.sqlQueries.Add(1)
|
||||
tag, err := s.pool.Exec(qCtx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT $1::uuid, $2::uuid, $3::uuid, $4, $5::timestamptz
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $2::uuid AND user_id = $3::uuid
|
||||
)
|
||||
`, msgID, chatID, callerID, req.Text, now)
|
||||
if err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
// Invalidate chat history cache immediately on write (unless in naive_ttl mode for Track 1 experiment)
|
||||
if s.rdb != nil && s.getCacheMode() == "write_through_versioned" {
|
||||
rCtx, rCancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
verKey := "chat_ver:" + chatID
|
||||
if err := s.rdb.Incr(rCtx, verKey).Err(); err != nil {
|
||||
log.Printf("WARN: redis cache version increment failed: %v", err)
|
||||
} else {
|
||||
_ = s.rdb.Expire(rCtx, verKey, 10*time.Minute).Err()
|
||||
}
|
||||
rCancel()
|
||||
}
|
||||
|
||||
return &model.Message{
|
||||
ID: msgID,
|
||||
ChatID: chatID,
|
||||
SenderID: callerID,
|
||||
Text: req.Text,
|
||||
CreatedAt: FormatTime(now),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) checkChatMembership(ctx context.Context, chatID, callerID, mode string) (bool, error) {
|
||||
memKey := fmt.Sprintf("chat_mem:%s:%s", chatID, callerID)
|
||||
if s.rdb != nil && mode != "disabled" {
|
||||
rCtx, rCancel := context.WithTimeout(ctx, 200*time.Millisecond)
|
||||
val, err := s.rdb.Get(rCtx, memKey).Result()
|
||||
rCancel()
|
||||
if err == nil {
|
||||
return val == "1", nil
|
||||
}
|
||||
}
|
||||
|
||||
queryMembership := func() (bool, error) {
|
||||
qCtx, cancel := context.WithTimeout(ctx, s.queryTimeout)
|
||||
defer cancel()
|
||||
var isMember bool
|
||||
s.sqlQueries.Add(1)
|
||||
err := s.pool.QueryRow(qCtx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid
|
||||
)
|
||||
`, chatID, callerID).Scan(&isMember)
|
||||
if err != nil {
|
||||
return false, classifyDBError(err)
|
||||
}
|
||||
if s.rdb != nil && mode != "disabled" {
|
||||
rCtx, rCancel := context.WithTimeout(ctx, 200*time.Millisecond)
|
||||
strVal := "0"
|
||||
if isMember {
|
||||
strVal = "1"
|
||||
}
|
||||
_ = s.rdb.Set(rCtx, memKey, strVal, 10*time.Minute).Err()
|
||||
rCancel()
|
||||
}
|
||||
return isMember, nil
|
||||
}
|
||||
|
||||
if mode == "write_through_versioned" {
|
||||
res, err, _ := s.sfGroup.Do(memKey, func() (interface{}, error) {
|
||||
return queryMembership()
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return res.(bool), nil
|
||||
}
|
||||
return queryMembership()
|
||||
}
|
||||
|
||||
func (s *PostgresStore) ListMessages(ctx context.Context, callerID, chatID string, limit int, cursorStr string) (*model.MessagePage, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, fmt.Errorf("%w: limit must be between 1 and 100", ErrBadRequest)
|
||||
}
|
||||
|
||||
scope := "msgs:" + chatID
|
||||
var hasCursor bool
|
||||
var cursorTime time.Time
|
||||
var cursorID string
|
||||
if cursorStr != "" {
|
||||
var err error
|
||||
cursorTime, cursorID, err = DecodeCursor(cursorStr, scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hasCursor = true
|
||||
}
|
||||
|
||||
mode := s.getCacheMode()
|
||||
|
||||
// 1. Always enforce membership check before returning cached or DB history
|
||||
isMember, err := s.checkChatMembership(ctx, chatID, callerID, mode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !isMember {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
// 2. Determine cache key
|
||||
var cacheKey string
|
||||
if s.rdb != nil && mode != "disabled" {
|
||||
if mode == "naive_ttl" {
|
||||
cacheKey = fmt.Sprintf("msg_page:%s:naive:l%d:c%s", chatID, limit, cursorStr)
|
||||
} else {
|
||||
rCtx, rCancel := context.WithTimeout(ctx, 200*time.Millisecond)
|
||||
ver, err := s.rdb.Get(rCtx, "chat_ver:"+chatID).Int64()
|
||||
rCancel()
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
log.Printf("WARN: redis version read failed (bypassing cache): %v", err)
|
||||
cacheKey = ""
|
||||
} else {
|
||||
cacheKey = fmt.Sprintf("msg_page:%s:v%d:l%d:c%s", chatID, ver, limit, cursorStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Check cache
|
||||
if cacheKey != "" {
|
||||
rCtx, rCancel := context.WithTimeout(ctx, 200*time.Millisecond)
|
||||
cachedBytes, err := s.rdb.Get(rCtx, cacheKey).Bytes()
|
||||
rCancel()
|
||||
if err == nil {
|
||||
var page model.MessagePage
|
||||
if json.Unmarshal(cachedBytes, &page) == nil {
|
||||
s.cacheHits.Add(1)
|
||||
return &page, nil
|
||||
}
|
||||
} else if !errors.Is(err, redis.Nil) {
|
||||
log.Printf("WARN: redis page read failed (falling back to PostgreSQL): %v", err)
|
||||
}
|
||||
s.cacheMisses.Add(1)
|
||||
}
|
||||
|
||||
fetchFromDB := func() (*model.MessagePage, error) {
|
||||
dbCtx, dbCancel := context.WithTimeout(ctx, s.queryTimeout)
|
||||
defer dbCancel()
|
||||
|
||||
var rows pgx.Rows
|
||||
var qErr error
|
||||
s.sqlQueries.Add(1)
|
||||
if !hasCursor {
|
||||
rows, qErr = s.pool.Query(dbCtx, `
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1::uuid
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $2
|
||||
`, chatID, limit+1)
|
||||
} else {
|
||||
rows, qErr = s.pool.Query(dbCtx, `
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1::uuid
|
||||
AND (created_at, id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $4
|
||||
`, chatID, cursorTime, cursorID, limit+1)
|
||||
}
|
||||
if qErr != nil {
|
||||
return nil, classifyDBError(qErr)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]model.Message, 0, limit)
|
||||
for rows.Next() {
|
||||
var m model.Message
|
||||
var createdAt time.Time
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &createdAt); err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
m.CreatedAt = FormatTime(createdAt)
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
var nextCursor *string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
c := EncodeCursor(scope, last.CreatedAt, last.ID)
|
||||
nextCursor = &c
|
||||
}
|
||||
|
||||
page := &model.MessagePage{
|
||||
Items: items,
|
||||
NextCursor: nextCursor,
|
||||
}
|
||||
|
||||
if cacheKey != "" && s.rdb != nil {
|
||||
if payload, mErr := json.Marshal(page); mErr == nil {
|
||||
rCtx, rCancel := context.WithTimeout(ctx, 200*time.Millisecond)
|
||||
ttl := 30 * time.Second
|
||||
if mode == "naive_ttl" {
|
||||
ttl = 5 * time.Second
|
||||
}
|
||||
_ = s.rdb.Set(rCtx, cacheKey, payload, ttl).Err()
|
||||
rCancel()
|
||||
}
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// 4. Use singleflight in write_through_versioned mode to prevent cache stampede!
|
||||
if mode == "write_through_versioned" && cacheKey != "" {
|
||||
res, err, shared := s.sfGroup.Do(cacheKey, func() (interface{}, error) {
|
||||
return fetchFromDB()
|
||||
})
|
||||
if shared {
|
||||
s.singleflightShared.Add(1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res.(*model.MessagePage), nil
|
||||
}
|
||||
|
||||
return fetchFromDB()
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"messenger/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrBadRequest = errors.New("bad request")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrUnavailable = errors.New("service unavailable")
|
||||
|
||||
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
)
|
||||
|
||||
const TimestampFormat = "2006-01-02T15:04:05.000000Z"
|
||||
|
||||
func FormatTime(t time.Time) string {
|
||||
return t.UTC().Truncate(time.Microsecond).Format(TimestampFormat)
|
||||
}
|
||||
|
||||
func NowUTC() time.Time {
|
||||
return time.Now().UTC().Truncate(time.Microsecond)
|
||||
}
|
||||
|
||||
type StoreStats struct {
|
||||
SQLQueries int64 `json:"sql_queries"`
|
||||
CacheHits int64 `json:"cache_hits"`
|
||||
CacheMisses int64 `json:"cache_misses"`
|
||||
SingleflightShared int64 `json:"singleflight_shared"`
|
||||
CacheMode string `json:"cache_mode"`
|
||||
RedisConnected bool `json:"redis_connected"`
|
||||
}
|
||||
|
||||
type Store interface {
|
||||
Ready(ctx context.Context) error
|
||||
CreateUser(ctx context.Context, req model.CreateUserRequest) (*model.User, error)
|
||||
AuthenticateAndCreateSession(ctx context.Context, username, password string, ttlSeconds int) (*model.Session, error)
|
||||
GetUserByToken(ctx context.Context, rawToken string) (*model.User, error)
|
||||
RevokeSession(ctx context.Context, rawToken string) error
|
||||
CreateChat(ctx context.Context, callerID string, req model.CreateChatRequest) (*model.Chat, error)
|
||||
ListChats(ctx context.Context, callerID string, limit int, cursorStr string) (*model.ChatPage, error)
|
||||
GetChat(ctx context.Context, callerID, chatID string) (*model.Chat, error)
|
||||
CreateMessage(ctx context.Context, callerID, chatID string, req model.CreateMessageRequest) (*model.Message, error)
|
||||
ListMessages(ctx context.Context, callerID, chatID string, limit int, cursorStr string) (*model.MessagePage, error)
|
||||
Stats(ctx context.Context) StoreStats
|
||||
ResetStats()
|
||||
SetCacheMode(mode string)
|
||||
Close()
|
||||
}
|
||||
|
||||
func EncodeCursor(scope, timestamp, id string) string {
|
||||
data := model.CursorData{
|
||||
Scope: scope,
|
||||
Time: timestamp,
|
||||
ID: id,
|
||||
}
|
||||
b, _ := json.Marshal(data)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func DecodeCursor(cursorStr, expectedScope string) (time.Time, string, error) {
|
||||
b, err := base64.RawURLEncoding.DecodeString(cursorStr)
|
||||
if err != nil {
|
||||
b, err = base64.URLEncoding.DecodeString(cursorStr)
|
||||
if err != nil {
|
||||
b, err = base64.StdEncoding.DecodeString(cursorStr)
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrBadRequest
|
||||
}
|
||||
}
|
||||
}
|
||||
var data model.CursorData
|
||||
if err := json.Unmarshal(b, &data); err != nil {
|
||||
return time.Time{}, "", ErrBadRequest
|
||||
}
|
||||
if data.Scope != expectedScope || data.Time == "" || data.ID == "" {
|
||||
return time.Time{}, "", ErrBadRequest
|
||||
}
|
||||
if _, err := uuid.Parse(data.ID); err != nil {
|
||||
return time.Time{}, "", ErrBadRequest
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, data.Time)
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrBadRequest
|
||||
}
|
||||
return t.UTC().Truncate(time.Microsecond), data.ID, nil
|
||||
}
|
||||
Reference in New Issue
Block a user