Перенести актуальную lab2 как базу lab3
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// CreateChat commits the chat and every member together, rolling back on any failure.
|
||||
func (s *Store) CreateChat(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
if err := tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES(@id,@title) RETURNING created_at`, pgx.StrictNamedArgs{"id": chat.ID, "title": chat.Title}).Scan(&chat.CreatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) SELECT @chat,id FROM unnest(@members::uuid[]) AS member(id)`, pgx.StrictNamedArgs{"chat": chat.ID, "members": chat.MemberIDs})
|
||||
return err
|
||||
})
|
||||
return chat, normalize(err)
|
||||
}
|
||||
|
||||
// Chat reads a chat and its immutable membership in one snapshot.
|
||||
func (s *Store) Chat(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var chat dto.ChatDTO
|
||||
err := s.pool.QueryRow(ctx, `SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)
|
||||
FROM chats c WHERE c.id=@id`, pgx.StrictNamedArgs{"id": id}).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
||||
return chat, normalize(err)
|
||||
}
|
||||
|
||||
// Chats returns the requested keyset page of chats visible to a user.
|
||||
func (s *Store) Chats(ctx context.Context, userID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)
|
||||
FROM chats c JOIN chat_members m ON m.chat_id=c.id
|
||||
WHERE m.user_id=@user AND (c.created_at,c.id)>(@time,@id) ORDER BY c.created_at,c.id LIMIT @limit`, pgx.StrictNamedArgs{
|
||||
"user": userID, "time": position.CreatedAt, "id": position.ID, "limit": limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, normalize(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
chats := make([]dto.ChatDTO, 0)
|
||||
for rows.Next() {
|
||||
var chat dto.ChatDTO
|
||||
if err := rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
|
||||
return nil, normalize(err)
|
||||
}
|
||||
chats = append(chats, chat)
|
||||
}
|
||||
return chats, normalize(rows.Err())
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// TestNormalizeUnavailable classifies dependency failures while retaining their causes.
|
||||
func TestNormalizeUnavailable(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
}{
|
||||
{"deadline", context.DeadlineExceeded},
|
||||
{"closed stream", io.EOF},
|
||||
{"truncated stream", io.ErrUnexpectedEOF},
|
||||
{"network", &net.OpError{Op: "dial", Net: "tcp", Err: errors.New("refused")}},
|
||||
{"connection exception", &pgconn.PgError{Code: "08006"}},
|
||||
{"connection limit", &pgconn.PgError{Code: "53300"}},
|
||||
{"shutdown", &pgconn.PgError{Code: "57P01"}},
|
||||
{"crash", &pgconn.PgError{Code: "57P02"}},
|
||||
{"starting", &pgconn.PgError{Code: "57P03"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := normalize(fmt.Errorf("operation failed: %w", tc.err))
|
||||
if !errors.Is(err, store.ErrUnavailable) || !errors.Is(err, tc.err) {
|
||||
t.Fatalf("failure category or cause lost: %T", tc.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeUnexpected preserves programming errors instead of misclassifying them as outages.
|
||||
func TestNormalizeUnexpected(t *testing.T) {
|
||||
for _, code := range []string{"42601", "23503", "42P01"} {
|
||||
t.Run(code, func(t *testing.T) {
|
||||
err := &pgconn.PgError{Code: code}
|
||||
if normalize(err) != err {
|
||||
t.Fatal("unexpected SQL error was reclassified")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// CreateMessage serializes timestamps on the owning chat and atomically appends a message.
|
||||
func (s *Store) CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
if err := tx.QueryRow(ctx, `UPDATE chats SET last_message_at=GREATEST(clock_timestamp(),last_message_at+interval '1 microsecond')
|
||||
WHERE id=@chat RETURNING last_message_at`, pgx.StrictNamedArgs{"chat": message.ChatID}).Scan(&message.CreatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES(@id,@chat,@sender,@text,@time)`, pgx.StrictNamedArgs{
|
||||
"id": message.ID, "chat": message.ChatID, "sender": message.SenderID, "text": message.Text, "time": message.CreatedAt,
|
||||
})
|
||||
return err
|
||||
})
|
||||
return message, normalize(err)
|
||||
}
|
||||
|
||||
// Messages reads an indexed keyset page without scanning earlier history.
|
||||
func (s *Store) Messages(ctx context.Context, chatID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages
|
||||
WHERE chat_id=@chat AND (created_at,id)>(@time,@id) ORDER BY created_at,id LIMIT @limit`, pgx.StrictNamedArgs{
|
||||
"chat": chatID, "time": position.CreatedAt, "id": position.ID, "limit": limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, normalize(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
messages := make([]dto.MessageDTO, 0)
|
||||
for rows.Next() {
|
||||
var message dto.MessageDTO
|
||||
if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt); err != nil {
|
||||
return nil, normalize(err)
|
||||
}
|
||||
messages = append(messages, message)
|
||||
}
|
||||
return messages, normalize(rows.Err())
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL UNIQUE,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
last_message_at timestamptz NOT NULL DEFAULT '-infinity'
|
||||
);
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
PRIMARY KEY(chat_id,user_id)
|
||||
);
|
||||
CREATE INDEX chat_members_user ON chat_members(user_id,chat_id);
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
sender_id uuid NOT NULL REFERENCES users(id),
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
FOREIGN KEY(chat_id,sender_id) REFERENCES chat_members(chat_id,user_id)
|
||||
);
|
||||
CREATE INDEX messages_history ON messages(chat_id,created_at,id);
|
||||
CREATE TABLE sessions (
|
||||
token_hash text PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX sessions_expiry ON sessions(expires_at);
|
||||
@@ -0,0 +1,36 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// SaveSession persists an absolute expiry and a token digest in PostgreSQL.
|
||||
func (s *Store) SaveSession(ctx context.Context, hash string, userID uuid.UUID, expiry time.Time) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(ctx, `INSERT INTO sessions(token_hash,user_id,expires_at) VALUES(@hash,@user,@expiry)`, pgx.StrictNamedArgs{
|
||||
"hash": hash, "user": userID, "expiry": expiry,
|
||||
})
|
||||
return normalize(err)
|
||||
}
|
||||
|
||||
// SessionUser rejects absent, revoked and expired sessions using database time.
|
||||
func (s *Store) SessionUser(ctx context.Context, hash string) (uuid.UUID, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var id uuid.UUID
|
||||
err := s.pool.QueryRow(ctx, `SELECT user_id FROM sessions WHERE token_hash=@hash AND expires_at>clock_timestamp()`, pgx.StrictNamedArgs{"hash": hash}).Scan(&id)
|
||||
return id, normalize(err)
|
||||
}
|
||||
|
||||
// RevokeSession deletes the authoritative session before logout succeeds.
|
||||
func (s *Store) RevokeSession(ctx context.Context, hash string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash=@hash`, pgx.StrictNamedArgs{"hash": hash})
|
||||
return normalize(err)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// Package postgres persists messenger records in PostgreSQL.
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
//go:embed migrations/001_initial.sql
|
||||
var initialMigration string
|
||||
|
||||
const migrationLockID = 202602
|
||||
|
||||
// Options bounds database resource use.
|
||||
type Options struct {
|
||||
// URL identifies the isolated application database.
|
||||
URL string
|
||||
// MaxConnections bounds concurrent database connections.
|
||||
MaxConnections int32
|
||||
// Timeout bounds each persistence operation.
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Store owns the PostgreSQL pool; Start and Close belong to application lifecycle.
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
var _ store.Interface = (*Store)(nil)
|
||||
|
||||
// New validates options and builds a lazy pool without opening connections.
|
||||
func New(options Options) (*Store, error) {
|
||||
if options.URL == "" || options.MaxConnections < 1 || options.Timeout <= 0 {
|
||||
return nil, fmt.Errorf("database URL, pool bound and timeout are required")
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(options.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid database configuration")
|
||||
}
|
||||
cfg.AfterConnect = func(_ context.Context, conn *pgx.Conn) error {
|
||||
conn.TypeMap().RegisterType(&pgtype.Type{Name: "timestamptz", OID: pgtype.TimestamptzOID, Codec: &pgtype.TimestamptzCodec{ScanLocation: time.UTC}})
|
||||
return nil
|
||||
}
|
||||
cfg.MaxConns = options.MaxConnections
|
||||
cfg.ConnConfig.ConnectTimeout = options.Timeout
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Store{pool: pool, timeout: options.Timeout}, nil
|
||||
}
|
||||
|
||||
// Start verifies connectivity and applies versioned migrations under a transaction lock.
|
||||
func (s *Store) Start(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock(@id)", pgx.StrictNamedArgs{"id": migrationLockID}); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY)"); err != nil {
|
||||
return err
|
||||
}
|
||||
var exists bool
|
||||
if err := tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=1)").Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, initialMigration); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES(1)")
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// Close releases owned pool resources after serving has stopped.
|
||||
func (s *Store) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
// Ping checks whether mandatory persistence can serve requests.
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
return s.pool.Ping(ctx)
|
||||
}
|
||||
|
||||
// normalize translates expected database errors without exposing SQL to higher layers.
|
||||
func normalize(err error) error {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return store.ErrNotFound
|
||||
}
|
||||
if databaseError, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
if databaseError.Code == "23505" {
|
||||
return store.ErrConflict
|
||||
}
|
||||
if strings.HasPrefix(databaseError.Code, "08") || strings.HasPrefix(databaseError.Code, "53") ||
|
||||
databaseError.Code == "57P01" || databaseError.Code == "57P02" || databaseError.Code == "57P03" {
|
||||
return fmt.Errorf("%w: %w", store.ErrUnavailable, err)
|
||||
}
|
||||
}
|
||||
var networkError net.Error
|
||||
var connectError *pgconn.ConnectError
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) ||
|
||||
errors.As(err, &networkError) || errors.As(err, &connectError) || pgconn.SafeToRetry(err) {
|
||||
return fmt.Errorf("%w: %w", store.ErrUnavailable, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// testStore creates an isolated schema inside the explicitly configured test database.
|
||||
func testStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
url := os.Getenv("TEST_DATABASE_URL")
|
||||
if url == "" {
|
||||
t.Skip("TEST_DATABASE_URL is required for PostgreSQL integration tests")
|
||||
}
|
||||
admin, err := pgx.Connect(t.Context(), url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
schema := "test_" + uuid.New().String()[:8]
|
||||
identifier := pgx.Identifier{schema}.Sanitize()
|
||||
if _, err := admin.Exec(t.Context(), "CREATE SCHEMA "+identifier); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
separator := "?"
|
||||
if containsQuery(url) {
|
||||
separator = "&"
|
||||
}
|
||||
s, err := New(Options{URL: url + separator + "search_path=" + schema, MaxConnections: 4, Timeout: 3 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
s.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if _, err := admin.Exec(ctx, "DROP SCHEMA "+identifier+" CASCADE"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if err := admin.Close(ctx); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if err := s.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// containsQuery identifies URL parameters without exposing credentials in test logs.
|
||||
func containsQuery(value string) bool {
|
||||
for _, char := range value {
|
||||
if char == '?' {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// fixtureUser creates an independent profile for a persistence scenario.
|
||||
func fixtureUser(t *testing.T, s *Store) dto.UserDTO {
|
||||
t.Helper()
|
||||
user, err := s.Register(t.Context(), dto.UserDTO{ID: uuid.New(), Username: "u_" + uuid.NewString()[:8], DisplayName: "Test"}, "test-hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
// fixtureChat creates a chat containing an existing user.
|
||||
func fixtureChat(t *testing.T, s *Store, user dto.UserDTO) dto.ChatDTO {
|
||||
t.Helper()
|
||||
chat, err := s.CreateChat(t.Context(), dto.ChatDTO{ID: uuid.New(), Title: "Test", MemberIDs: []uuid.UUID{user.ID}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return chat
|
||||
}
|
||||
|
||||
// TestMigrationsRepeat verifies idempotent schema initialization.
|
||||
func TestMigrationsRepeat(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
if err := s.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
read, err := s.User(t.Context(), user.ID)
|
||||
if err != nil || read.ID != user.ID || read.CreatedAt.Location() != time.UTC {
|
||||
t.Fatalf("migration changed data or UTC: %v", err)
|
||||
}
|
||||
if err := s.Ping(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistrationRace verifies database uniqueness under concurrent registration.
|
||||
func TestRegistrationRace(t *testing.T) {
|
||||
s := testStore(t)
|
||||
outcomes := make(chan error, 12)
|
||||
var wg sync.WaitGroup
|
||||
for range 12 {
|
||||
wg.Go(func() {
|
||||
_, err := s.Register(t.Context(), dto.UserDTO{ID: uuid.New(), Username: "same", DisplayName: "Test"}, "hash")
|
||||
outcomes <- err
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(outcomes)
|
||||
successes := 0
|
||||
for err := range outcomes {
|
||||
if err == nil {
|
||||
successes++
|
||||
} else if !errors.Is(err, store.ErrConflict) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if successes != 1 {
|
||||
t.Fatalf("got %d successful registrations", successes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateChatRollsBack verifies failure of membership insertion leaves no chat.
|
||||
func TestCreateChatRollsBack(t *testing.T) {
|
||||
s := testStore(t)
|
||||
id := uuid.New()
|
||||
_, err := s.CreateChat(t.Context(), dto.ChatDTO{ID: id, Title: "Rollback", MemberIDs: []uuid.UUID{uuid.New()}})
|
||||
if err == nil {
|
||||
t.Fatal("foreign key failure absent")
|
||||
}
|
||||
if _, err := s.Chat(t.Context(), id); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("chat survived rollback: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatPageUsesMembershipAndCursor verifies one compound visibility/page invariant.
|
||||
func TestChatPageUsesMembershipAndCursor(t *testing.T) {
|
||||
s := testStore(t)
|
||||
owner := fixtureUser(t, s)
|
||||
outsider := fixtureUser(t, s)
|
||||
first := fixtureChat(t, s, owner)
|
||||
second := fixtureChat(t, s, owner)
|
||||
fixtureChat(t, s, outsider)
|
||||
page, err := s.Chats(t.Context(), owner.ID, dto.PositionDTO{CreatedAt: first.CreatedAt, ID: first.ID}, 10)
|
||||
if err != nil || len(page) != 1 || page[0].ID != second.ID || len(page[0].MemberIDs) != 1 {
|
||||
t.Fatalf("invalid membership page: %+v %v", page, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMessagePageOrdersConcurrentWrites verifies monotonic durable ordering and continuation.
|
||||
func TestMessagePageOrdersConcurrentWrites(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
chat := fixtureChat(t, s, user)
|
||||
var wg sync.WaitGroup
|
||||
failures := make(chan error, 20)
|
||||
for range 20 {
|
||||
wg.Go(func() {
|
||||
_, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: user.ID, Text: "synthetic"})
|
||||
failures <- err
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(failures)
|
||||
for err := range failures {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
page, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{}, 10)
|
||||
if err != nil || len(page) != 10 {
|
||||
t.Fatalf("first page: %d %v", len(page), err)
|
||||
}
|
||||
for index := 1; index < len(page); index++ {
|
||||
if !page[index].CreatedAt.After(page[index-1].CreatedAt) {
|
||||
t.Fatal("timestamps are not monotonic")
|
||||
}
|
||||
}
|
||||
last := page[len(page)-1]
|
||||
next, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{CreatedAt: last.CreatedAt, ID: last.ID}, 20)
|
||||
if err != nil || len(next) != 10 || !next[0].CreatedAt.After(last.CreatedAt) {
|
||||
t.Fatalf("continuation: %d %v", len(next), err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCredentialsReadsStoredHash checks credential lookup independently of public profiles.
|
||||
func TestCredentialsReadsStoredHash(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
got, hash, err := s.Credentials(t.Context(), user.Username)
|
||||
if err != nil || got.ID != user.ID || hash != "test-hash" {
|
||||
t.Fatalf("credentials mismatch: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUsersExistChecksAllIDs verifies the set membership contract.
|
||||
func TestUsersExistChecksAllIDs(t *testing.T) {
|
||||
for _, missing := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "all exist", true: "missing member"}[missing], func(t *testing.T) {
|
||||
s := testStore(t)
|
||||
ids := []uuid.UUID{fixtureUser(t, s).ID}
|
||||
if missing {
|
||||
ids = append(ids, uuid.New())
|
||||
}
|
||||
exists, err := s.UsersExist(t.Context(), ids)
|
||||
if err != nil || exists == missing {
|
||||
t.Fatalf("exists=%v error=%v", exists, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSessionExpiry rejects persisted sessions whose absolute deadline has passed.
|
||||
func TestSessionExpiry(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
if err := s.SaveSession(t.Context(), "expired", user.ID, time.Now().Add(-time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.SessionUser(t.Context(), "expired"); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("expired session accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSessionRevocation removes a still-valid session from the source of truth.
|
||||
func TestSessionRevocation(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
if err := s.SaveSession(t.Context(), "live", user.ID, time.Now().Add(time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.RevokeSession(t.Context(), "live"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.SessionUser(t.Context(), "live"); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("revoked session accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSessionResolvesOwner verifies a live session's immutable identity.
|
||||
func TestSessionResolvesOwner(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
if err := s.SaveSession(t.Context(), "live", user.ID, time.Now().Add(time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := s.SessionUser(t.Context(), "live")
|
||||
if err != nil || id != user.ID {
|
||||
t.Fatalf("invalid owner: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewRejectsInvalidOptions verifies pool construction errors without connecting.
|
||||
func TestNewRejectsInvalidOptions(t *testing.T) {
|
||||
for _, options := range []Options{{}, {URL: "://invalid", MaxConnections: 1, Timeout: time.Second}} {
|
||||
if _, err := New(options); err == nil {
|
||||
t.Fatal("invalid options accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateMessageMissingChat reports a typed missing-record error.
|
||||
func TestCreateMessageMissingChat(t *testing.T) {
|
||||
s := testStore(t)
|
||||
_, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: uuid.New(), SenderID: uuid.New(), Text: "test"})
|
||||
if !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMessagesCanceledReturnsError verifies bounded cancellation before query execution.
|
||||
func TestMessagesCanceledReturnsError(t *testing.T) {
|
||||
s := testStore(t)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if _, err := s.Messages(ctx, uuid.New(), dto.PositionDTO{}, 10); err == nil {
|
||||
t.Fatal("canceled query succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatsCanceledReturnsError verifies bounded cancellation of membership pages.
|
||||
func TestChatsCanceledReturnsError(t *testing.T) {
|
||||
s := testStore(t)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if _, err := s.Chats(ctx, uuid.New(), dto.PositionDTO{}, 10); err == nil {
|
||||
t.Fatal("canceled query succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigrationCancellationReturnsError checks startup cancellation before migration work.
|
||||
func TestMigrationCancellationReturnsError(t *testing.T) {
|
||||
s := testStore(t)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if err := s.Start(ctx); err == nil {
|
||||
t.Fatal("canceled migration succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigrationFailureRollsBackVersion verifies a failed migration is never marked applied.
|
||||
func TestMigrationFailureRollsBackVersion(t *testing.T) {
|
||||
s := testStore(t)
|
||||
if _, err := s.pool.Exec(t.Context(), "DELETE FROM schema_migrations"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Start(t.Context()); err == nil {
|
||||
t.Fatal("conflicting unversioned schema accepted")
|
||||
}
|
||||
var count int
|
||||
if err := s.pool.QueryRow(t.Context(), "SELECT count(*) FROM schema_migrations").Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatal("failed migration version committed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigrationRejectsBrokenVersionLedger verifies corrupt migration metadata stops startup safely.
|
||||
func TestMigrationRejectsBrokenVersionLedger(t *testing.T) {
|
||||
s := testStore(t)
|
||||
if _, err := s.pool.Exec(t.Context(), "ALTER TABLE schema_migrations RENAME COLUMN version TO broken_version"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Start(t.Context()); err == nil {
|
||||
t.Fatal("broken version ledger accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// CreateUser inserts a profile and enforces uniqueness inside PostgreSQL.
|
||||
func (s *Store) CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error) {
|
||||
return s.Register(ctx, user, "")
|
||||
}
|
||||
|
||||
// Register atomically stores a profile and its password hash.
|
||||
func (s *Store) Register(ctx context.Context, user dto.UserDTO, passwordHash string) (dto.UserDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
err := s.pool.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash)
|
||||
VALUES(@id,@username,@display_name,@password_hash) RETURNING created_at`, pgx.StrictNamedArgs{
|
||||
"id": user.ID,
|
||||
"username": user.Username,
|
||||
"display_name": user.DisplayName,
|
||||
"password_hash": passwordHash,
|
||||
}).Scan(&user.CreatedAt)
|
||||
return user, normalize(err)
|
||||
}
|
||||
|
||||
// User reads a profile without credentials.
|
||||
func (s *Store) User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var user dto.UserDTO
|
||||
err := s.pool.QueryRow(ctx, `SELECT id,username,display_name,created_at FROM users WHERE id=@id`, pgx.StrictNamedArgs{"id": id}).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
return user, normalize(err)
|
||||
}
|
||||
|
||||
// Credentials reads the account needed for password verification.
|
||||
func (s *Store) Credentials(ctx context.Context, username string) (dto.UserDTO, string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var user dto.UserDTO
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx, `SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=@username`, pgx.StrictNamedArgs{"username": username}).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
|
||||
return user, hash, normalize(err)
|
||||
}
|
||||
|
||||
// UsersExist checks all distinct requested identifiers in one bounded query.
|
||||
func (s *Store) UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var exists bool
|
||||
err := s.pool.QueryRow(ctx, `SELECT NOT EXISTS (SELECT id FROM unnest(@ids::uuid[]) AS requested(id)
|
||||
WHERE NOT EXISTS (SELECT 1 FROM users WHERE users.id=requested.id))`, pgx.StrictNamedArgs{"ids": ids}).Scan(&exists)
|
||||
return exists, normalize(err)
|
||||
}
|
||||
Reference in New Issue
Block a user