feat: add PostgreSQL persistence and sessions

This commit is contained in:
2026-09-24 10:50:20 +03:00
parent 65003b6119
commit 872b69f90e
21 changed files with 2264 additions and 0 deletions
+148
View File
@@ -0,0 +1,148 @@
package config
import (
"errors"
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Address string
DatabaseURL string
CacheURL string
SessionTTL time.Duration
DBMaxConns int32
DBMinConns int32
ConnectTimeout time.Duration
RequestTimeout time.Duration
SwaggerPort string
}
func Load() (Config, error) {
host, err := requiredEnv("APP_HOST")
if err != nil {
return Config{}, err
}
port, err := requiredPort("APP_PORT")
if err != nil {
return Config{}, err
}
databaseURL, err := secretFromEnv("DATABASE_URL_FILE")
if err != nil {
return Config{}, err
}
cacheURL, err := secretFromEnv("CACHE_URL_FILE")
if err != nil {
return Config{}, err
}
if store, err := requiredEnv("SESSION_STORE"); err != nil {
return Config{}, err
} else if store != "valkey" {
return Config{}, errors.New("SESSION_STORE must be valkey")
}
ttlSeconds, err := requiredPositiveInt("SESSION_TTL_SECONDS")
if err != nil {
return Config{}, err
}
maxConns, err := intEnv("DB_MAX_CONNS", 10, 1, 100)
if err != nil {
return Config{}, err
}
minConns, err := intEnv("DB_MIN_CONNS", 1, 0, maxConns)
if err != nil {
return Config{}, err
}
connectSeconds, err := intEnv("DEPENDENCY_TIMEOUT_SECONDS", 5, 1, 60)
if err != nil {
return Config{}, err
}
swaggerPort := os.Getenv("SWAGGER_PORT")
if swaggerPort == "" {
swaggerPort = "8081"
}
if _, err := parsePort(swaggerPort); err != nil {
return Config{}, fmt.Errorf("SWAGGER_PORT: %w", err)
}
return Config{
Address: net.JoinHostPort(host, port),
DatabaseURL: databaseURL,
CacheURL: cacheURL,
SessionTTL: time.Duration(ttlSeconds) * time.Second,
DBMaxConns: int32(maxConns),
DBMinConns: int32(minConns),
ConnectTimeout: time.Duration(connectSeconds) * time.Second,
RequestTimeout: time.Duration(connectSeconds) * time.Second,
SwaggerPort: swaggerPort,
}, nil
}
func requiredEnv(name string) (string, error) {
value := strings.TrimSpace(os.Getenv(name))
if value == "" {
return "", fmt.Errorf("%s is required", name)
}
return value, nil
}
func requiredPort(name string) (string, error) {
value, err := requiredEnv(name)
if err != nil {
return "", err
}
if _, err := parsePort(value); err != nil {
return "", fmt.Errorf("%s: %w", name, err)
}
return value, nil
}
func parsePort(value string) (int, error) {
port, err := strconv.Atoi(value)
if err != nil || port < 1 || port > 65535 {
return 0, errors.New("must be between 1 and 65535")
}
return port, nil
}
func requiredPositiveInt(name string) (int, error) {
value, err := requiredEnv(name)
if err != nil {
return 0, err
}
parsed, err := strconv.Atoi(value)
if err != nil || parsed <= 0 {
return 0, fmt.Errorf("%s must be a positive integer", name)
}
return parsed, nil
}
func intEnv(name string, fallback, minimum, maximum int) (int, error) {
value := os.Getenv(name)
if value == "" {
return fallback, nil
}
parsed, err := strconv.Atoi(value)
if err != nil || parsed < minimum || parsed > maximum {
return 0, fmt.Errorf("%s must be between %d and %d", name, minimum, maximum)
}
return parsed, nil
}
func secretFromEnv(name string) (string, error) {
path, err := requiredEnv(name)
if err != nil {
return "", err
}
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read %s: %w", name, err)
}
value := strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("%s points to an empty file", name)
}
return value, nil
}
+81
View File
@@ -0,0 +1,81 @@
package database
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/dizi/mtusi2026lab2/migrations"
)
type Config struct {
URL string
MinConnections int32
MaxConnections int32
MaxConnectionAge time.Duration
MaxConnectionIdle time.Duration
HealthCheckPeriod time.Duration
ConnectTimeout time.Duration
MigrationTimeout time.Duration
}
func Open(ctx context.Context, config Config) (*pgxpool.Pool, error) {
if err := validateConfig(config); err != nil {
return nil, err
}
poolConfig, err := pgxpool.ParseConfig(config.URL)
if err != nil {
return nil, fmt.Errorf("parse database configuration: %w", err)
}
poolConfig.MinConns = config.MinConnections
poolConfig.MaxConns = config.MaxConnections
poolConfig.MaxConnLifetime = config.MaxConnectionAge
poolConfig.MaxConnIdleTime = config.MaxConnectionIdle
poolConfig.HealthCheckPeriod = config.HealthCheckPeriod
connectCtx, cancel := context.WithTimeout(ctx, config.ConnectTimeout)
defer cancel()
pool, err := pgxpool.NewWithConfig(connectCtx, poolConfig)
if err != nil {
return nil, fmt.Errorf("create database pool: %w", err)
}
if err := pool.Ping(connectCtx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
migrationCtx, cancel := context.WithTimeout(ctx, config.MigrationTimeout)
defer cancel()
if err := applyMigrations(migrationCtx, pool, migrations.FS); err != nil {
pool.Close()
return nil, err
}
return pool, nil
}
func validateConfig(config Config) error {
switch {
case config.URL == "":
return fmt.Errorf("database URL is required")
case config.MinConnections < 0:
return fmt.Errorf("minimum database connections must not be negative")
case config.MaxConnections < 1:
return fmt.Errorf("maximum database connections must be positive")
case config.MinConnections > config.MaxConnections:
return fmt.Errorf("minimum database connections exceed maximum")
case config.MaxConnectionAge <= 0:
return fmt.Errorf("maximum database connection age must be positive")
case config.MaxConnectionIdle <= 0:
return fmt.Errorf("maximum database connection idle time must be positive")
case config.HealthCheckPeriod <= 0:
return fmt.Errorf("database health check period must be positive")
case config.ConnectTimeout <= 0:
return fmt.Errorf("database connection timeout must be positive")
case config.MigrationTimeout <= 0:
return fmt.Errorf("database migration timeout must be positive")
default:
return nil
}
}
+150
View File
@@ -0,0 +1,150 @@
package database
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io/fs"
"path/filepath"
"regexp"
"sort"
"strconv"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
const (
migrationLockID int64 = 0x4d54555349324c42
migrationUnlockTimeout = 5 * time.Second
)
var migrationNamePattern = regexp.MustCompile(`^(\d+)_([a-z0-9_]+)\.sql$`)
type migration struct {
version int64
name string
checksum string
sql string
}
func applyMigrations(ctx context.Context, pool *pgxpool.Pool, migrationFS fs.FS) (returnErr error) {
migrations, err := readMigrations(migrationFS)
if err != nil {
return err
}
connection, err := pool.Acquire(ctx)
if err != nil {
return fmt.Errorf("acquire connection for migrations: %w", err)
}
defer connection.Release()
if _, err := connection.Exec(ctx, "SELECT pg_advisory_lock($1)", migrationLockID); err != nil {
return fmt.Errorf("lock migrations: %w", err)
}
defer func() {
unlockCtx, cancel := context.WithTimeout(context.Background(), migrationUnlockTimeout)
defer cancel()
if _, err := connection.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", migrationLockID); err != nil {
_ = connection.Conn().Close(unlockCtx)
if returnErr == nil {
returnErr = fmt.Errorf("unlock migrations: %w", err)
}
}
}()
if _, err := connection.Exec(ctx, `
CREATE TABLE IF NOT EXISTS schema_migrations (
version BIGINT PRIMARY KEY,
name TEXT NOT NULL,
checksum TEXT NOT NULL,
applied_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
)`); err != nil {
return fmt.Errorf("create migration history: %w", err)
}
for _, migration := range migrations {
if err := applyMigration(ctx, connection, migration); err != nil {
return err
}
}
return nil
}
func readMigrations(migrationFS fs.FS) ([]migration, error) {
entries, err := fs.ReadDir(migrationFS, ".")
if err != nil {
return nil, fmt.Errorf("read embedded migrations: %w", err)
}
migrations := make([]migration, 0, len(entries))
versions := make(map[int64]string)
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".sql" {
continue
}
matches := migrationNamePattern.FindStringSubmatch(entry.Name())
if matches == nil {
return nil, fmt.Errorf("invalid migration filename %q", entry.Name())
}
version, err := strconv.ParseInt(matches[1], 10, 64)
if err != nil || version < 1 {
return nil, fmt.Errorf("invalid migration version in %q", entry.Name())
}
if previous, exists := versions[version]; exists {
return nil, fmt.Errorf("migration version %d is used by %q and %q", version, previous, entry.Name())
}
data, err := fs.ReadFile(migrationFS, entry.Name())
if err != nil {
return nil, fmt.Errorf("read migration %q: %w", entry.Name(), err)
}
hash := sha256.Sum256(data)
versions[version] = entry.Name()
migrations = append(migrations, migration{
version: version,
name: entry.Name(),
checksum: hex.EncodeToString(hash[:]),
sql: string(data),
})
}
if len(migrations) == 0 {
return nil, errors.New("no database migrations found")
}
sort.Slice(migrations, func(i, j int) bool {
return migrations[i].version < migrations[j].version
})
return migrations, nil
}
func applyMigration(ctx context.Context, connection *pgxpool.Conn, migration migration) error {
var checksum string
err := connection.QueryRow(ctx, "SELECT checksum FROM schema_migrations WHERE version = $1", migration.version).Scan(&checksum)
switch {
case err == nil && checksum != migration.checksum:
return fmt.Errorf("migration %q checksum does not match applied version", migration.name)
case err == nil:
return nil
case !errors.Is(err, pgx.ErrNoRows):
return fmt.Errorf("read migration %q state: %w", migration.name, err)
}
transaction, err := connection.Begin(ctx)
if err != nil {
return fmt.Errorf("begin migration %q: %w", migration.name, err)
}
defer func() {
_ = transaction.Rollback(context.WithoutCancel(ctx))
}()
if _, err := transaction.Exec(ctx, migration.sql, pgx.QueryExecModeSimpleProtocol); err != nil {
return fmt.Errorf("apply migration %q: %w", migration.name, err)
}
if _, err := transaction.Exec(ctx, `
INSERT INTO schema_migrations (version, name, checksum)
VALUES ($1, $2, $3)`, migration.version, migration.name, migration.checksum); err != nil {
return fmt.Errorf("record migration %q: %w", migration.name, err)
}
if err := transaction.Commit(ctx); err != nil {
return fmt.Errorf("commit migration %q: %w", migration.name, err)
}
return nil
}
+33
View File
@@ -0,0 +1,33 @@
package messenger
import (
"context"
"time"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
)
type Repository interface {
Ping(context.Context) error
CreateUser(context.Context, string, string, string) (model.User, error)
UserByID(context.Context, string) (model.User, error)
UserByUsername(context.Context, string) (model.UserCredentials, error)
CreateChat(context.Context, string, []string, string) (model.Chat, error)
ChatForUser(context.Context, string, string) (model.Chat, error)
ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error)
CreateMessage(context.Context, string, string, string) (model.Message, error)
ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error)
}
type SessionStore interface {
Ping(context.Context) error
Create(context.Context, string, time.Duration) (string, time.Time, error)
UserID(context.Context, string) (string, error)
Delete(context.Context, string) error
}
type Passwords interface {
Hash(string) (string, error)
Verify(string, string) (bool, error)
DummyHash() string
}
+60
View File
@@ -0,0 +1,60 @@
package messenger
import (
"encoding/json"
"net/http"
)
const (
errorCodeInvalidRequest = "invalid_request"
errorCodeUnauthorized = "unauthorized"
errorCodeNotFound = "not_found"
errorCodeInternal = "internal_error"
errorCodeUnsupportedMediaType = "unsupported_media_type"
errorCodePayloadTooLarge = "payload_too_large"
errorCodeUnavailable = "unavailable"
errorCodeConflict = "conflict"
)
type apiError struct {
status int
code string
message string
}
func methodNotAllowed(w http.ResponseWriter, allowed string) *apiError {
w.Header().Set("Allow", allowed)
return &apiError{http.StatusMethodNotAllowed, errorCodeInvalidRequest, "method not allowed"}
}
func invalidRequest() *apiError {
return &apiError{http.StatusBadRequest, errorCodeInvalidRequest, "invalid request"}
}
func unauthorized() *apiError {
return &apiError{http.StatusUnauthorized, errorCodeUnauthorized, "authentication required"}
}
func notFound() *apiError {
return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"}
}
func internalError() *apiError {
return &apiError{http.StatusInternalServerError, errorCodeInternal, "internal server error"}
}
func unavailable() *apiError {
return &apiError{http.StatusServiceUnavailable, errorCodeUnavailable, "service unavailable"}
}
func writeError(w http.ResponseWriter, requestID string, err *apiError) {
writeJSON(w, err.status, map[string]any{"error": map[string]string{
"code": err.code, "message": err.message, "request_id": requestID,
}})
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
+357
View File
@@ -0,0 +1,357 @@
package messenger
import (
"context"
"errors"
"io"
"net/http"
"regexp"
"strings"
"time"
"unicode/utf8"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/postgres"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/session"
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func (s *Server) live(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return nil
}
func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
if !s.ready.Load() {
return unavailable()
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := s.repository.Ping(ctx); err != nil {
return unavailable()
}
if err := s.sessions.Ping(ctx); err != nil {
return unavailable()
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return nil
}
func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
var input struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !usernamePattern.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validPassword(input.Password) {
return invalidRequest()
}
passwordHash, err := s.passwords.Hash(input.Password)
if err != nil {
return internalError()
}
user, err := s.repository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
if errors.Is(err, postgres.ErrConflict) {
return &apiError{http.StatusConflict, errorCodeConflict, "username already exists"}
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, user)
return nil
}
func validPassword(value string) bool {
length := utf8.RuneCountInString(value)
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && length >= 12 && length <= 128
}
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
body, err := io.ReadAll(io.LimitReader(r.Body, 1))
if err != nil || len(body) != 0 {
return invalidRequest()
}
username, passwordValue, ok := singleBasicAuth(r)
if !ok {
return unauthorized()
}
credentials, err := s.repository.UserByUsername(r.Context(), username)
if errors.Is(err, postgres.ErrNotFound) {
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
return internalError()
}
return unauthorized()
}
if err != nil {
return unavailable()
}
verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
if err != nil {
return internalError()
}
if !verified {
return unauthorized()
}
token, expiresAt, err := s.sessions.Create(r.Context(), credentials.ID, s.sessionTTL)
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User User `json:"user"`
}{token, "Bearer", model.FormatTime(expiresAt), credentials.User})
return nil
}
func singleBasicAuth(r *http.Request) (string, string, bool) {
if len(r.Header.Values("Authorization")) != 1 {
return "", "", false
}
username, passwordValue, ok := r.BasicAuth()
return username, passwordValue, ok && username != ""
}
func (s *Server) revokeSession(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodDelete {
return methodNotAllowed(w, http.MethodDelete)
}
_, token, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
if err := s.sessions.Delete(r.Context(), token); errors.Is(err, session.ErrNotFound) {
return unauthorized()
} else if err != nil {
return unavailable()
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) me(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, err := s.authenticate(r)
if err != nil {
return err
}
writeJSON(w, http.StatusOK, user)
return nil
}
func (s *Server) chats(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost && r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
if r.Method == http.MethodGet {
return s.listChats(w, r, user)
}
var input struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
return invalidRequest()
}
members := make(map[string]struct{}, len(input.MemberIDs))
for i, memberID := range input.MemberIDs {
canonical, valid := canonicalID(memberID)
if !valid {
return invalidRequest()
}
if _, duplicate := members[canonical]; duplicate {
return invalidRequest()
}
members[canonical] = struct{}{}
input.MemberIDs[i] = canonical
}
if _, included := members[user.ID]; !included {
return invalidRequest()
}
chat, err := s.repository.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
if errors.Is(err, postgres.ErrInvalidMembers) {
return invalidRequest()
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, chat)
return nil
}
func (s *Server) listChats(w http.ResponseWriter, r *http.Request, user User) *apiError {
limit, cursor, err := pageParams(r, "chat", user.ID)
if err != nil {
return err
}
items, hasNext, listErr := s.repository.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
if errors.Is(listErr, postgres.ErrInvalidCursor) {
return invalidRequest()
}
if listErr != nil {
return unavailable()
}
if items == nil {
items = []Chat{}
}
var next *string
if hasNext {
last := items[len(items)-1]
value := encodeCursor("chat", user.ID, last.CreatedAt, last.ID)
next = &value
}
writeJSON(w, http.StatusOK, struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}{items, next})
return nil
}
func (s *Server) chat(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
chat, err := s.repository.ChatForUser(r.Context(), chatID, user.ID)
if errors.Is(err, postgres.ErrNotFound) {
return notFound()
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusOK, chat)
return nil
}
func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost && r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
if r.Method == http.MethodGet {
return s.listMessages(w, r, user, chatID)
}
var input struct {
Text string `json:"text"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !validText(input.Text, 4000) {
return invalidRequest()
}
message, err := s.repository.CreateMessage(r.Context(), chatID, user.ID, input.Text)
if errors.Is(err, postgres.ErrNotFound) {
return notFound()
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, message)
return nil
}
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User, chatID string) *apiError {
limit, cursor, err := pageParams(r, "message", chatID)
if err != nil {
return err
}
items, hasNext, listErr := s.repository.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
if errors.Is(listErr, postgres.ErrNotFound) {
return notFound()
}
if errors.Is(listErr, postgres.ErrInvalidCursor) {
return invalidRequest()
}
if listErr != nil {
return unavailable()
}
if items == nil {
items = []Message{}
}
var next *string
if hasNext {
last := items[len(items)-1]
value := encodeCursor("message", chatID, last.CreatedAt, last.ID)
next = &value
}
writeJSON(w, http.StatusOK, struct {
Items []Message `json:"items"`
NextCursor *string `json:"next_cursor"`
}{items, next})
return nil
}
func cursorPosition(cursor *pageCursor) *model.Position {
if cursor == nil {
return nil
}
return &model.Position{CreatedAt: cursor.Time, ID: cursor.ID}
}
func (s *Server) authenticate(r *http.Request) (User, string, *apiError) {
values := r.Header.Values("Authorization")
if len(values) != 1 {
return User{}, "", unauthorized()
}
scheme, token, found := strings.Cut(values[0], " ")
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t\r\n") {
return User{}, "", unauthorized()
}
userID, err := s.sessions.UserID(r.Context(), token)
if errors.Is(err, session.ErrNotFound) || errors.Is(err, session.ErrInvalidToken) {
return User{}, "", unauthorized()
}
if err != nil {
return User{}, "", unavailable()
}
user, err := s.repository.UserByID(r.Context(), userID)
if errors.Is(err, postgres.ErrNotFound) {
_ = s.sessions.Delete(r.Context(), token)
return User{}, "", unauthorized()
}
if err != nil {
return User{}, "", unavailable()
}
return user, token, nil
}
+75
View File
@@ -0,0 +1,75 @@
package messenger
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type metrics struct {
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
inFlight prometheus.Gauge
handler http.Handler
}
func newMetrics() *metrics {
registry := prometheus.NewRegistry()
result := &metrics{
requests: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "requests_total",
Help: "Completed HTTP requests.",
}, []string{"method", "route", "status_class"}),
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "request_duration_seconds",
Help: "HTTP request duration in seconds.",
Buckets: prometheus.DefBuckets,
}, []string{"method", "route"}),
inFlight: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "requests_in_flight",
Help: "HTTP requests currently being served.",
}),
}
registry.MustRegister(
result.requests,
result.duration,
result.inFlight,
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
result.handler = promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
return result
}
func (m *metrics) observe(r *http.Request, status int, started time.Time) {
route := routeTemplate(r.URL.Path)
m.requests.WithLabelValues(r.Method, route, strconv.Itoa(status/100)+"xx").Inc()
m.duration.WithLabelValues(r.Method, route).Observe(time.Since(started).Seconds())
}
func routeTemplate(path string) string {
switch path {
case "/health/live", "/health/ready", "/metrics", "/api/v1/users", "/api/v1/users/me",
"/api/v1/auth/sessions", "/api/v1/auth/sessions/current", "/api/v1/chats":
return path
}
parts := strings.Split(strings.Trim(path, "/"), "/")
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
return "/api/v1/chats/{chat_id}"
}
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
return "/api/v1/chats/{chat_id}/messages"
}
return "unknown"
}
+29
View File
@@ -0,0 +1,29 @@
package messenger
import (
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
"github.com/google/uuid"
)
type User = model.User
type Chat = model.Chat
type Message = model.Message
func newID() (string, error) {
id, err := uuid.NewRandom()
if err != nil {
return "", err
}
return id.String(), nil
}
func canonicalID(value string) (string, bool) {
if len(value) != 36 {
return "", false
}
id, err := uuid.Parse(value)
if err != nil {
return "", false
}
return id.String(), true
}
+116
View File
@@ -0,0 +1,116 @@
package messenger
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unicode/utf8"
)
const maxRequestBytes = 1 << 20
func readJSON(w http.ResponseWriter, r *http.Request, target any) *apiError {
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
return &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "expected application/json"}
}
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBytes)
data, err := io.ReadAll(r.Body)
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "request body too large"}
}
return invalidRequest()
}
if !utf8.Valid(data) {
return invalidRequest()
}
var object map[string]json.RawMessage
if err := json.Unmarshal(data, &object); err != nil || object == nil {
return invalidRequest()
}
normalized, err := json.Marshal(object)
if err != nil {
return invalidRequest()
}
decoder := json.NewDecoder(bytes.NewReader(normalized))
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
return invalidRequest()
}
return nil
}
func validText(value string, maxRunes int) bool {
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes
}
type pageCursor struct {
Kind string `json:"kind"`
Resource string `json:"resource"`
Time time.Time `json:"time"`
ID string `json:"id"`
}
func pageParams(r *http.Request, kind, resource string) (int, *pageCursor, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return 0, nil, invalidRequest()
}
for key := range query {
if key != "limit" && key != "cursor" {
return 0, nil, invalidRequest()
}
if len(query[key]) != 1 {
return 0, nil, invalidRequest()
}
}
limit := 50
if value, present := query["limit"]; present {
parsed, err := strconv.Atoi(value[0])
if err != nil || parsed < 1 || parsed > 100 {
return 0, nil, invalidRequest()
}
limit = parsed
}
if value, present := query["cursor"]; present {
cursor, valid := decodeCursor(value[0], kind, resource)
if !valid {
return 0, nil, invalidRequest()
}
return limit, cursor, nil
}
return limit, nil, nil
}
func encodeCursor(kind, resource string, createdAt time.Time, id string) string {
data, _ := json.Marshal(pageCursor{kind, resource, createdAt, id})
return base64.RawURLEncoding.EncodeToString(data)
}
func decodeCursor(value, kind, resource string) (*pageCursor, bool) {
data, err := base64.RawURLEncoding.DecodeString(value)
if err != nil {
return nil, false
}
var cursor pageCursor
if err := json.Unmarshal(data, &cursor); err != nil || cursor.Kind != kind || cursor.Resource != resource {
return nil, false
}
if cursor.Time.IsZero() {
return nil, false
}
if _, valid := canonicalID(cursor.ID); !valid {
return nil, false
}
return &cursor, true
}
+41
View File
@@ -0,0 +1,41 @@
package messenger
import (
"net/http"
"strings"
)
type requestHandler func(http.ResponseWriter, *http.Request) *apiError
func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError {
var handler requestHandler
switch r.URL.Path {
case "/health/live":
handler = s.live
case "/health/ready":
handler = s.readiness
case "/metrics":
s.metrics.handler.ServeHTTP(w, r)
return nil
case "/api/v1/users":
handler = s.users
case "/api/v1/users/me":
handler = s.me
case "/api/v1/auth/sessions":
handler = s.createSession
case "/api/v1/auth/sessions/current":
handler = s.revokeSession
case "/api/v1/chats":
handler = s.chats
default:
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
handler = s.chat
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
handler = s.messages
} else {
return notFound()
}
}
return handler(w, r)
}
+102
View File
@@ -0,0 +1,102 @@
package messenger
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"time"
)
type Server struct {
repository Repository
sessions SessionStore
passwords Passwords
sessionTTL time.Duration
requestTTL time.Duration
logger *slog.Logger
swaggerPort string
metrics *metrics
ready atomic.Bool
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func NewServer(logger *slog.Logger, repository Repository, sessions SessionStore, passwords Passwords, sessionTTL, requestTTL time.Duration, swaggerPort string) *Server {
s := &Server{
repository: repository, sessions: sessions, passwords: passwords,
sessionTTL: sessionTTL, requestTTL: requestTTL, logger: logger, swaggerPort: swaggerPort, metrics: newMetrics(),
}
s.ready.Store(true)
return s
}
func (s *Server) SetReady(ready bool) {
s.ready.Store(ready)
}
func (s *Server) Handler() http.Handler {
return http.HandlerFunc(s.serve)
}
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
requestID, err := newID()
if err != nil {
http.Error(w, "server unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("X-Request-Id", requestID)
w.Header().Set("Cache-Control", "no-store")
wrapped := &statusWriter{ResponseWriter: w, status: http.StatusOK}
started := time.Now()
s.metrics.inFlight.Inc()
defer func() {
s.metrics.inFlight.Dec()
if recovered := recover(); recovered != nil {
s.logger.Error("request panic", "request_id", requestID, "method", r.Method, "path", r.URL.Path)
if wrapped.status == http.StatusOK {
writeError(wrapped, requestID, internalError())
}
}
s.metrics.observe(r, wrapped.status, started)
s.logger.Info("request", "request_id", requestID, "method", r.Method, "path", r.URL.Path, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
}()
if s.allowSwaggerOrigin(wrapped, r) && r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
wrapped.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
wrapped.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
wrapped.WriteHeader(http.StatusNoContent)
return
}
ctx, cancel := context.WithTimeout(r.Context(), s.requestTTL)
defer cancel()
r = r.WithContext(ctx)
if apiErr := s.route(wrapped, r); apiErr != nil {
if apiErr.status == http.StatusUnauthorized {
challenge := `Bearer realm="messenger"`
if r.URL.Path == "/api/v1/auth/sessions" {
challenge = `Basic realm="messenger", charset="UTF-8"`
}
wrapped.Header().Set("WWW-Authenticate", challenge)
}
writeError(wrapped, requestID, apiErr)
}
}
func (s *Server) allowSwaggerOrigin(w http.ResponseWriter, r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin != "http://localhost:"+s.swaggerPort && origin != "http://127.0.0.1:"+s.swaggerPort {
return false
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id")
w.Header().Add("Vary", "Origin")
return true
}
+79
View File
@@ -0,0 +1,79 @@
package model
import (
"encoding/json"
"time"
)
const timestampLayout = "2006-01-02T15:04:05.000000Z"
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt time.Time `json:"created_at"`
}
type UserCredentials struct {
User
PasswordHash string `json:"-"`
}
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 Position struct {
CreatedAt time.Time
ID string
}
func (u User) MarshalJSON() ([]byte, error) {
type response struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
return json.Marshal(response{u.ID, u.Username, u.DisplayName, formatTime(u.CreatedAt)})
}
func (c Chat) MarshalJSON() ([]byte, error) {
type response struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt string `json:"created_at"`
}
return json.Marshal(response{c.ID, c.Title, c.MemberIDs, formatTime(c.CreatedAt)})
}
func (m Message) MarshalJSON() ([]byte, error) {
type response struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
}
return json.Marshal(response{m.ID, m.ChatID, m.SenderID, m.Text, formatTime(m.CreatedAt)})
}
func FormatTime(value time.Time) string {
return formatTime(value)
}
func formatTime(value time.Time) string {
return value.UTC().Format(timestampLayout)
}
+100
View File
@@ -0,0 +1,100 @@
package password
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const (
MemoryKiB uint32 = 64 * 1024
Iterations uint32 = 3
Parallelism uint8 = 2
SaltLength = 16
KeyLength uint32 = 32
)
var ErrInvalidHash = errors.New("invalid password hash")
var dummyHash = encode(
make([]byte, SaltLength),
argon2.IDKey([]byte("invalid-user-password"), make([]byte, SaltLength), Iterations, MemoryKiB, Parallelism, KeyLength),
)
type Hasher struct{}
func (Hasher) Hash(value string) (string, error) {
return Hash(value)
}
func (Hasher) Verify(value, encodedHash string) (bool, error) {
return Verify(value, encodedHash)
}
func (Hasher) DummyHash() string {
return dummyHash
}
func Hash(value string) (string, error) {
salt := make([]byte, SaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate password salt: %w", err)
}
digest := argon2.IDKey([]byte(value), salt, Iterations, MemoryKiB, Parallelism, KeyLength)
return encode(salt, digest), nil
}
func encode(salt, digest []byte) string {
return fmt.Sprintf(
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
MemoryKiB,
Iterations,
Parallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(digest),
)
}
func Verify(value, encodedHash string) (bool, error) {
salt, digest, err := decode(encodedHash)
if err != nil {
return false, err
}
actual := argon2.IDKey([]byte(value), salt, Iterations, MemoryKiB, Parallelism, KeyLength)
return subtle.ConstantTimeCompare(actual, digest) == 1, nil
}
func decode(encodedHash string) ([]byte, []byte, error) {
parts := strings.Split(encodedHash, "$")
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
return nil, nil, ErrInvalidHash
}
if parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
return nil, nil, ErrInvalidHash
}
if parts[3] != fmt.Sprintf("m=%d,t=%d,p=%d", MemoryKiB, Iterations, Parallelism) {
return nil, nil, ErrInvalidHash
}
salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[4])
if err != nil || len(salt) != SaltLength {
return nil, nil, ErrInvalidHash
}
digest, err := base64.RawStdEncoding.Strict().DecodeString(parts[5])
if err != nil || len(digest) != int(KeyLength) {
return nil, nil, ErrInvalidHash
}
return salt, digest, nil
}
+10
View File
@@ -0,0 +1,10 @@
package postgres
import "errors"
var (
ErrConflict = errors.New("conflict")
ErrNotFound = errors.New("not found")
ErrInvalidMembers = errors.New("invalid members")
ErrInvalidCursor = errors.New("invalid cursor")
)
+469
View File
@@ -0,0 +1,469 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
)
type Store struct {
pool *pgxpool.Pool
}
func New(pool *pgxpool.Pool) *Store {
return &Store{pool: pool}
}
func (s *Store) Ping(ctx context.Context) error {
return s.pool.Ping(ctx)
}
func (s *Store) CreateUser(
ctx context.Context,
username string,
displayName string,
passwordHash string,
) (model.User, error) {
const query = `
INSERT INTO users (id, username, display_name, password_hash)
VALUES ($1, $2, $3, $4)
RETURNING id, username, display_name, created_at`
var user model.User
err := s.pool.QueryRow(ctx, query, uuid.NewString(), username, displayName, passwordHash).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
)
if isUniqueViolation(err) {
return model.User{}, ErrConflict
}
if err != nil {
return model.User{}, fmt.Errorf("create user: %w", err)
}
return user, nil
}
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
const query = `
SELECT id, username, display_name, created_at
FROM users
WHERE id = $1`
var user model.User
err := s.pool.QueryRow(ctx, query, id).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, ErrNotFound
}
if err != nil {
return model.User{}, fmt.Errorf("get user by id: %w", err)
}
return user, nil
}
func (s *Store) UserByUsername(ctx context.Context, username string) (model.UserCredentials, error) {
const query = `
SELECT id, username, display_name, created_at, password_hash
FROM users
WHERE username = $1`
var credentials model.UserCredentials
err := s.pool.QueryRow(ctx, query, username).Scan(
&credentials.ID,
&credentials.Username,
&credentials.DisplayName,
&credentials.CreatedAt,
&credentials.PasswordHash,
)
if errors.Is(err, pgx.ErrNoRows) {
return model.UserCredentials{}, ErrNotFound
}
if err != nil {
return model.UserCredentials{}, fmt.Errorf("get user by username: %w", err)
}
return credentials, nil
}
func (s *Store) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
callerID string,
) (model.Chat, error) {
if !validMembers(memberIDs, callerID) {
return model.Chat{}, ErrInvalidMembers
}
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return model.Chat{}, fmt.Errorf("begin create chat transaction: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
valid, err := allUsersExist(ctx, tx, memberIDs)
if err != nil {
return model.Chat{}, err
}
if !valid {
return model.Chat{}, ErrInvalidMembers
}
chat, err := insertChat(ctx, tx, title)
if err != nil {
return model.Chat{}, err
}
if err := insertMembers(ctx, tx, chat.ID, memberIDs); err != nil {
return model.Chat{}, err
}
if err := tx.Commit(ctx); err != nil {
return model.Chat{}, fmt.Errorf("commit create chat transaction: %w", err)
}
chat.MemberIDs = append([]string(nil), memberIDs...)
return chat, nil
}
func validMembers(memberIDs []string, callerID string) bool {
callerUUID, err := uuid.Parse(callerID)
if err != nil {
return false
}
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
callerIncluded := false
for _, memberID := range memberIDs {
memberUUID, err := uuid.Parse(memberID)
if err != nil {
return false
}
if _, exists := seen[memberUUID]; exists {
return false
}
seen[memberUUID] = struct{}{}
callerIncluded = callerIncluded || memberUUID == callerUUID
}
return callerIncluded
}
func allUsersExist(ctx context.Context, tx pgx.Tx, memberIDs []string) (bool, error) {
const query = `
SELECT count(*)
FROM users
WHERE id::text = ANY($1)`
var count int
if err := tx.QueryRow(ctx, query, memberIDs).Scan(&count); err != nil {
return false, fmt.Errorf("check chat members: %w", err)
}
return count == len(memberIDs), nil
}
func insertChat(ctx context.Context, tx pgx.Tx, title string) (model.Chat, error) {
const query = `
INSERT INTO chats (id, title)
VALUES ($1, $2)
RETURNING id, title, created_at`
var chat model.Chat
if err := tx.QueryRow(ctx, query, uuid.NewString(), title).Scan(&chat.ID, &chat.Title, &chat.CreatedAt); err != nil {
return model.Chat{}, fmt.Errorf("insert chat: %w", err)
}
return chat, nil
}
func insertMembers(ctx context.Context, tx pgx.Tx, chatID string, memberIDs []string) error {
const query = `
INSERT INTO chat_members (chat_id, user_id, position)
VALUES ($1, $2, $3)`
batch := &pgx.Batch{}
for position, memberID := range memberIDs {
batch.Queue(query, chatID, memberID, position)
}
results := tx.SendBatch(ctx, batch)
defer func() { _ = results.Close() }()
for range memberIDs {
if _, err := results.Exec(); err != nil {
return fmt.Errorf("insert chat member: %w", err)
}
}
if err := results.Close(); err != nil {
return fmt.Errorf("close chat members batch: %w", err)
}
return nil
}
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
const query = `
SELECT c.id, c.title, c.created_at,
array_agg(cm.user_id::text ORDER BY cm.position)
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE c.id = $1
AND EXISTS (
SELECT 1
FROM chat_members visible
WHERE visible.chat_id = c.id AND visible.user_id = $2
)
GROUP BY c.id, c.title, c.created_at`
var chat model.Chat
err := s.pool.QueryRow(ctx, query, chatID, userID).Scan(
&chat.ID,
&chat.Title,
&chat.CreatedAt,
&chat.MemberIDs,
)
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, ErrNotFound
}
if err != nil {
return model.Chat{}, fmt.Errorf("get chat for user: %w", err)
}
return chat, nil
}
func (s *Store) ListChats(
ctx context.Context,
userID string,
after *model.Position,
limit int,
) ([]model.Chat, bool, error) {
if after != nil {
valid, err := s.visibleChatPositionExists(ctx, userID, *after)
if err != nil {
return nil, false, err
}
if !valid {
return nil, false, ErrInvalidCursor
}
}
const query = `
SELECT c.id, c.title, c.created_at,
array_agg(all_members.user_id::text ORDER BY all_members.position)
FROM chats c
JOIN chat_members visible ON visible.chat_id = c.id AND visible.user_id = $1
JOIN chat_members all_members ON all_members.chat_id = c.id
WHERE ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid))
GROUP BY c.id, c.title, c.created_at
ORDER BY c.created_at, c.id
LIMIT $4`
var afterTime any
var afterID any
if after != nil {
afterTime = after.CreatedAt
afterID = after.ID
}
rows, err := s.pool.Query(ctx, query, userID, afterTime, afterID, limit+1)
if err != nil {
return nil, false, fmt.Errorf("list chats: %w", err)
}
defer rows.Close()
chats, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Chat](func(row pgx.CollectableRow) (model.Chat, error) {
var chat model.Chat
err := row.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
return chat, err
}))
if err != nil {
return nil, false, fmt.Errorf("scan chats: %w", err)
}
return page(chats, limit)
}
func (s *Store) visibleChatPositionExists(
ctx context.Context,
userID string,
position model.Position,
) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE cm.user_id = $1 AND c.created_at = $2 AND c.id = $3
)`
var exists bool
if err := s.pool.QueryRow(ctx, query, userID, position.CreatedAt, position.ID).Scan(&exists); err != nil {
return false, fmt.Errorf("validate chat cursor: %w", err)
}
return exists, nil
}
func (s *Store) CreateMessage(
ctx context.Context,
chatID string,
senderID string,
text string,
) (model.Message, error) {
const query = `
INSERT INTO messages (id, chat_id, sender_id, text)
SELECT $1, $2, $3, $4
WHERE EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $2 AND user_id = $3
)
RETURNING id, chat_id, sender_id, text, created_at`
var message model.Message
err := s.pool.QueryRow(ctx, query, uuid.NewString(), chatID, senderID, text).Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return model.Message{}, ErrNotFound
}
if err != nil {
return model.Message{}, fmt.Errorf("create message: %w", err)
}
return message, nil
}
func (s *Store) ListMessages(
ctx context.Context,
chatID string,
userID string,
after *model.Position,
limit int,
) ([]model.Message, bool, error) {
visible, err := s.chatVisible(ctx, chatID, userID)
if err != nil {
return nil, false, err
}
if !visible {
return nil, false, ErrNotFound
}
if after != nil {
valid, err := s.messagePositionExists(ctx, chatID, *after)
if err != nil {
return nil, false, err
}
if !valid {
return nil, false, ErrInvalidCursor
}
}
const query = `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1
AND ($2::timestamptz IS NULL OR (created_at, id) > ($2, $3::uuid))
ORDER BY created_at, id
LIMIT $4`
var afterTime any
var afterID any
if after != nil {
afterTime = after.CreatedAt
afterID = after.ID
}
rows, err := s.pool.Query(ctx, query, chatID, afterTime, afterID, limit+1)
if err != nil {
return nil, false, fmt.Errorf("list messages: %w", err)
}
defer rows.Close()
messages, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Message](func(row pgx.CollectableRow) (model.Message, error) {
var message model.Message
err := row.Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
)
return message, err
}))
if err != nil {
return nil, false, fmt.Errorf("scan messages: %w", err)
}
return page(messages, limit)
}
func (s *Store) chatVisible(ctx context.Context, chatID, userID string) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1 AND user_id = $2
)`
var exists bool
if err := s.pool.QueryRow(ctx, query, chatID, userID).Scan(&exists); err != nil {
return false, fmt.Errorf("check chat visibility: %w", err)
}
return exists, nil
}
func (s *Store) messagePositionExists(
ctx context.Context,
chatID string,
position model.Position,
) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1
FROM messages
WHERE chat_id = $1 AND created_at = $2 AND id = $3
)`
var exists bool
if err := s.pool.QueryRow(ctx, query, chatID, position.CreatedAt, position.ID).Scan(&exists); err != nil {
return false, fmt.Errorf("validate message cursor: %w", err)
}
return exists, nil
}
func page[T any](items []T, limit int) ([]T, bool, error) {
if limit < 1 {
return nil, false, fmt.Errorf("limit must be positive")
}
if len(items) <= limit {
return items, false, nil
}
return items[:limit], true, nil
}
func isUniqueViolation(err error) bool {
var postgresError *pgconn.PgError
return errors.As(err, &postgresError) && postgresError.Code == "23505"
}
+161
View File
@@ -0,0 +1,161 @@
package session
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/valkey-io/valkey-go"
)
const (
tokenLength = 32
keyPrefix = "session:"
)
var (
ErrNotFound = errors.New("session not found")
ErrInvalidToken = errors.New("invalid session token")
ErrInvalidRecord = errors.New("invalid session record")
ErrInvalidTTL = errors.New("invalid session TTL")
ErrTokenGeneration = errors.New("session token generation failed")
ErrStore = errors.New("session store failure")
)
type record struct {
UserID string `json:"user_id"`
ExpiresAt time.Time `json:"expires_at"`
}
type Store struct {
client valkey.Client
}
func New(rawURL string) (*Store, error) {
option, err := valkey.ParseURL(rawURL)
if err != nil {
return nil, fmt.Errorf("%w: parse Valkey URL: %w", ErrStore, err)
}
client, err := valkey.NewClient(option)
if err != nil {
return nil, fmt.Errorf("%w: create Valkey client: %w", ErrStore, err)
}
return &Store{client: client}, nil
}
func (s *Store) Create(ctx context.Context, userID string, ttl time.Duration) (string, time.Time, error) {
if strings.TrimSpace(userID) == "" {
return "", time.Time{}, ErrInvalidRecord
}
if ttl < time.Second {
return "", time.Time{}, ErrInvalidTTL
}
token, err := newToken()
if err != nil {
return "", time.Time{}, err
}
record := record{
UserID: userID,
ExpiresAt: time.Now().UTC().Add(ttl).Truncate(time.Microsecond),
}
payload, err := json.Marshal(record)
if err != nil {
return "", time.Time{}, fmt.Errorf("%w: encode session: %w", ErrStore, err)
}
command := s.client.B().Set().Key(s.key(token)).Value(valkey.BinaryString(payload)).Ex(ttl).Build()
if err := s.client.Do(ctx, command).Error(); err != nil {
return "", time.Time{}, fmt.Errorf("%w: create session: %w", ErrStore, err)
}
return token, record.ExpiresAt, nil
}
func newToken() (string, error) {
random := make([]byte, tokenLength)
if _, err := rand.Read(random); err != nil {
return "", fmt.Errorf("%w: %v", ErrTokenGeneration, err)
}
return base64.RawURLEncoding.EncodeToString(random), nil
}
func (s *Store) UserID(ctx context.Context, token string) (string, error) {
key, err := s.sessionKey(token)
if err != nil {
return "", err
}
payload, err := s.client.Do(ctx, s.client.B().Get().Key(key).Build()).AsBytes()
if valkey.IsValkeyNil(err) {
return "", ErrNotFound
}
if err != nil {
return "", fmt.Errorf("%w: get session: %w", ErrStore, err)
}
var record record
if err := json.Unmarshal(payload, &record); err != nil {
return "", fmt.Errorf("%w: decode session: %w", ErrStore, err)
}
if strings.TrimSpace(record.UserID) == "" || record.ExpiresAt.IsZero() {
return "", fmt.Errorf("%w: %w", ErrStore, ErrInvalidRecord)
}
if !record.ExpiresAt.After(time.Now()) {
return "", ErrNotFound
}
return record.UserID, nil
}
func (s *Store) Delete(ctx context.Context, token string) error {
key, err := s.sessionKey(token)
if err != nil {
return err
}
deleted, err := s.client.Do(ctx, s.client.B().Del().Key(key).Build()).AsInt64()
if err != nil {
return fmt.Errorf("%w: delete session: %w", ErrStore, err)
}
if deleted == 0 {
return ErrNotFound
}
return nil
}
func (s *Store) Ping(ctx context.Context) error {
if err := s.client.Do(ctx, s.client.B().Ping().Build()).Error(); err != nil {
return fmt.Errorf("%w: ping Valkey: %w", ErrStore, err)
}
return nil
}
func (s *Store) Close() error {
s.client.Close()
return nil
}
func (s *Store) sessionKey(token string) (string, error) {
decoded, err := base64.RawURLEncoding.Strict().DecodeString(token)
if err != nil || len(decoded) != tokenLength {
return "", ErrInvalidToken
}
return s.key(token), nil
}
func (s *Store) key(token string) string {
digest := sha256.Sum256([]byte(token))
return keyPrefix + hex.EncodeToString(digest[:])
}