This commit is contained in:
@@ -55,7 +55,7 @@ func writeServiceError(w http.ResponseWriter, err error, requestID string) {
|
||||
case errors.Is(err, services.ErrChatNotFound):
|
||||
writeError(w, 404, "not_found", "chat not found", requestID)
|
||||
default:
|
||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ func readyHandler(health *services.HealthService) http.HandlerFunc {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := health.Ready(ctx); err != nil {
|
||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, healthResponse{"ok"})
|
||||
|
||||
@@ -86,6 +86,10 @@ func listMessagesHandler(chats *services.ChatService, messages *services.Message
|
||||
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||
return
|
||||
}
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||
return
|
||||
}
|
||||
chat, err := chats.Get(r.Context(), userID, chatID)
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
|
||||
@@ -32,7 +32,7 @@ func authRequired(sessions *services.SessionService, next http.Handler) http.Han
|
||||
if err != nil {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), authenticatedUserKey{}, user.ID)))
|
||||
@@ -64,7 +64,7 @@ func sessionHandler(sessions *services.SessionService) http.HandlerFunc {
|
||||
}
|
||||
user, token, expires, valid, err := sessions.Login(r.Context(), username, password)
|
||||
if err != nil {
|
||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
return
|
||||
}
|
||||
if !valid {
|
||||
@@ -90,7 +90,7 @@ func logoutHandler(sessions *services.SessionService) http.HandlerFunc {
|
||||
}
|
||||
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
if err := sessions.Revoke(r.Context(), token); err != nil {
|
||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
|
||||
+15
-4
@@ -63,6 +63,13 @@ func main() {
|
||||
log.Fatalf("database initialization failed: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
redisAddress := os.Getenv("REDIS_ADDR")
|
||||
if redisAddress == "" {
|
||||
redisAddress = "redis:6379"
|
||||
}
|
||||
redisClient := repositories.NewRedisClient(redisAddress)
|
||||
defer redisClient.Close()
|
||||
sessionStore := repositories.NewSessionStore(redisClient, "messenger:session:")
|
||||
userStore := repositories.NewUserStore(db)
|
||||
chatStore := repositories.NewChatStore(db)
|
||||
messageStore := repositories.NewMessageStore(db)
|
||||
@@ -71,14 +78,18 @@ func main() {
|
||||
log.Fatal(err)
|
||||
}
|
||||
userService := services.NewUserService(userStore)
|
||||
sessionService := services.NewSessionService(userService, repositories.NewSessionStore(db), ttl)
|
||||
sessionService := services.NewSessionService(userService, sessionStore, ttl)
|
||||
chatService := services.NewChatService(chatStore)
|
||||
messageService := services.NewMessageService(messageStore)
|
||||
mux := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db)), userService, sessionService, chatService, messageService)
|
||||
mux := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db), sessionStore), userService, sessionService, chatService, messageService)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: serverAddress(),
|
||||
Handler: mux,
|
||||
Addr: serverAddress(),
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
shutdownContext, stop := signal.NotifyContext(
|
||||
|
||||
@@ -27,6 +27,8 @@ func NewChatStore(db *pgxpool.Pool) *ChatStore {
|
||||
var ErrUnknownMember = errors.New("unknown member")
|
||||
|
||||
func (s *ChatStore) Create(ctx context.Context, title string, memberIDs []string) (Chat, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
membersCopy := append([]string(nil), memberIDs...)
|
||||
chat := Chat{
|
||||
ID: uuid.New().String(),
|
||||
@@ -64,6 +66,8 @@ func (s *ChatStore) Create(ctx context.Context, title string, memberIDs []string
|
||||
}
|
||||
|
||||
func (s *ChatStore) GetByID(ctx context.Context, id string) (Chat, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
var chat Chat
|
||||
err := s.db.QueryRow(ctx, "SELECT id,title,created_at FROM chats WHERE id=$1", id).Scan(&chat.ID, &chat.Title, &chat.CreatedAt)
|
||||
if err != nil {
|
||||
@@ -86,6 +90,8 @@ func (s *ChatStore) GetByID(ctx context.Context, id string) (Chat, error) {
|
||||
}
|
||||
|
||||
func (s *ChatStore) ListPageForUser(ctx context.Context, userID string, cursor *ChatCursor, limit int) ([]Chat, bool, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
afterTime := time.Time{}
|
||||
afterID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != nil {
|
||||
|
||||
@@ -15,5 +15,7 @@ func NewHealthStore(db *pgxpool.Pool) *HealthStore {
|
||||
}
|
||||
|
||||
func (s *HealthStore) Ping(ctx context.Context) error {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
return s.db.Ping(ctx)
|
||||
}
|
||||
|
||||
@@ -30,6 +30,8 @@ func (s *MessageStore) Create(
|
||||
senderID string,
|
||||
text string,
|
||||
) (Message, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
message := Message{
|
||||
ID: uuid.New().String(),
|
||||
ChatID: chatID,
|
||||
@@ -48,6 +50,8 @@ func (s *MessageStore) ListPageByChat(
|
||||
cursor *MessageCursor,
|
||||
limit int,
|
||||
) ([]Message, bool, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
afterTime := time.Time{}
|
||||
afterID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != nil {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX sessions_expiry_idx ON sessions(expires_at);
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE sessions;
|
||||
@@ -0,0 +1,56 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var ErrSessionNotFound = errors.New("session not found")
|
||||
|
||||
type SessionStore struct {
|
||||
client *redis.Client
|
||||
prefix string
|
||||
}
|
||||
|
||||
func NewRedisClient(address string) *redis.Client {
|
||||
return redis.NewClient(&redis.Options{
|
||||
Addr: address, PoolSize: 10, MaxRetries: -1,
|
||||
DialTimeout: time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second,
|
||||
})
|
||||
}
|
||||
|
||||
func NewSessionStore(client *redis.Client, prefix string) *SessionStore {
|
||||
return &SessionStore{client: client, prefix: prefix}
|
||||
}
|
||||
|
||||
func (s *SessionStore) key(tokenHash []byte) string {
|
||||
return s.prefix + hex.EncodeToString(tokenHash)
|
||||
}
|
||||
|
||||
func (s *SessionStore) Create(ctx context.Context, tokenHash []byte, userID string, expires time.Time) error {
|
||||
ttl := time.Until(expires)
|
||||
if ttl <= 0 {
|
||||
return errors.New("session expiry must be in the future")
|
||||
}
|
||||
return s.client.Set(ctx, s.key(tokenHash), userID, ttl).Err()
|
||||
}
|
||||
|
||||
func (s *SessionStore) UserID(ctx context.Context, tokenHash []byte) (string, error) {
|
||||
id, err := s.client.Get(ctx, s.key(tokenHash)).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return "", ErrSessionNotFound
|
||||
}
|
||||
return id, err
|
||||
}
|
||||
|
||||
func (s *SessionStore) Revoke(ctx context.Context, tokenHash []byte) error {
|
||||
return s.client.Del(ctx, s.key(tokenHash)).Err()
|
||||
}
|
||||
|
||||
func (s *SessionStore) Ping(ctx context.Context) error {
|
||||
return s.client.Ping(ctx).Err()
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type SessionStore struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewSessionStore(db *pgxpool.Pool) *SessionStore {
|
||||
return &SessionStore{db: db}
|
||||
}
|
||||
|
||||
func (s *SessionStore) Create(ctx context.Context, tokenHash []byte, userID string, expires time.Time) error {
|
||||
_, err := s.db.Exec(ctx, "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,$3)", tokenHash, userID, expires)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SessionStore) User(ctx context.Context, tokenHash []byte) (User, error) {
|
||||
var user User
|
||||
err := s.db.QueryRow(ctx, `SELECT u.id,u.username,u.display_name,u.created_at FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=$1 AND s.expires_at>now()`, tokenHash).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *SessionStore) Revoke(ctx context.Context, tokenHash []byte) error {
|
||||
_, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", tokenHash)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
const queryTimeout = 5 * time.Second
|
||||
|
||||
func boundedQuery(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, queryTimeout)
|
||||
}
|
||||
@@ -26,6 +26,8 @@ func NewUserStore(db *pgxpool.Pool) *UserStore {
|
||||
}
|
||||
|
||||
func (s *UserStore) Create(ctx context.Context, username, displayName string, passwordHash []byte) (User, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
user := User{
|
||||
ID: uuid.New().String(),
|
||||
Username: username,
|
||||
@@ -38,12 +40,16 @@ func (s *UserStore) Create(ctx context.Context, username, displayName string, pa
|
||||
}
|
||||
|
||||
func (s *UserStore) GetByID(ctx context.Context, id string) (User, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
var user User
|
||||
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at FROM users WHERE id=$1", id).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *UserStore) GetCredentials(ctx context.Context, username string) (User, []byte, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
var user User
|
||||
var packedHash []byte
|
||||
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &packedHash)
|
||||
|
||||
@@ -7,13 +7,17 @@ import (
|
||||
)
|
||||
|
||||
type HealthService struct {
|
||||
health *repositories.HealthStore
|
||||
health *repositories.HealthStore
|
||||
sessions *repositories.SessionStore
|
||||
}
|
||||
|
||||
func NewHealthService(health *repositories.HealthStore) *HealthService {
|
||||
return &HealthService{health: health}
|
||||
func NewHealthService(health *repositories.HealthStore, sessions *repositories.SessionStore) *HealthService {
|
||||
return &HealthService{health: health, sessions: sessions}
|
||||
}
|
||||
|
||||
func (s *HealthService) Ready(ctx context.Context) error {
|
||||
return s.health.Ping(ctx)
|
||||
if err := s.health.Ping(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.sessions.Ping(ctx)
|
||||
}
|
||||
|
||||
@@ -63,8 +63,15 @@ func (s *SessionService) CreateForUser(ctx context.Context, userID string) (stri
|
||||
|
||||
func (s *SessionService) User(ctx context.Context, token string) (repositories.User, error) {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
user, err := s.sessions.User(ctx, hash[:])
|
||||
if repositories.NotFound(err) {
|
||||
id, err := s.sessions.UserID(ctx, hash[:])
|
||||
if errors.Is(err, repositories.ErrSessionNotFound) {
|
||||
return repositories.User{}, ErrInvalidSession
|
||||
}
|
||||
if err != nil {
|
||||
return repositories.User{}, err
|
||||
}
|
||||
user, err := s.users.Get(ctx, id)
|
||||
if errors.Is(err, ErrUnknownUser) {
|
||||
return repositories.User{}, ErrInvalidSession
|
||||
}
|
||||
return user, err
|
||||
|
||||
@@ -59,6 +59,9 @@ func (s *UserService) Authenticate(ctx context.Context, username, password strin
|
||||
return repositories.User{}, false, nil
|
||||
}
|
||||
user, packedHash, err := s.users.GetCredentials(ctx, username)
|
||||
if repositories.NotFound(err) {
|
||||
return repositories.User{}, false, nil
|
||||
}
|
||||
if err != nil || packedHash == nil {
|
||||
return repositories.User{}, false, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/handlers"
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func TestConcurrentRegistrationSameUsername(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
const body = `{"username":"alice","display_name":"Алиса","password":"lab2-test-password"}`
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
results := make(chan int, 2)
|
||||
for i := 0; i < 2; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(body))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
results <- w.Code
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
counts := map[int]int{}
|
||||
for status := range results {
|
||||
counts[status]++
|
||||
}
|
||||
if counts[201] != 1 || counts[409] != 1 {
|
||||
t.Fatalf("registration statuses: %v", counts)
|
||||
}
|
||||
var users int
|
||||
if err := f.db.QueryRow(context.Background(), "SELECT count(*) FROM users WHERE username='alice'").Scan(&users); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if users != 1 {
|
||||
t.Fatalf("stored %d users with the same username", users)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatTransactionRollsBackAfterMemberInsertFailure(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
alice, _ := createTestUser(t, f.users, "alice", "Алиса")
|
||||
bob, _ := createTestUser(t, f.users, "bob", "Боб")
|
||||
_, err := f.db.Exec(context.Background(), `CREATE FUNCTION reject_bob() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.user_id = '`+bob.ID+`'::uuid THEN RAISE EXCEPTION 'forced member failure'; END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER reject_bob_insert BEFORE INSERT ON chat_members FOR EACH ROW EXECUTE FUNCTION reject_bob();`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.chats.Create(context.Background(), "rollback-check", []string{alice.ID, bob.ID}); err == nil {
|
||||
t.Fatal("expected second member insertion to fail")
|
||||
}
|
||||
var chats, members int
|
||||
if err := f.db.QueryRow(context.Background(), "SELECT count(*) FROM chats WHERE title='rollback-check'").Scan(&chats); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.db.QueryRow(context.Background(), "SELECT count(*) FROM chat_members").Scan(&members); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if chats != 0 || members != 0 {
|
||||
t.Fatalf("transaction left chats=%d members=%d", chats, members)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortSessionTTLAndLogout(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Алиса")
|
||||
t.Setenv("SESSION_TTL_SECONDS", "2")
|
||||
ttl, err := services.SessionTTL()
|
||||
if err != nil || ttl != 2*time.Second {
|
||||
t.Fatalf("short TTL: %v, %v", ttl, err)
|
||||
}
|
||||
sessions := services.NewSessionService(services.NewUserService(f.users), f.sessionStore, ttl)
|
||||
router := handlers.NewRouter(nil, services.NewUserService(f.users), sessions, nil, nil)
|
||||
assertHTTPUser := func(token string, want int) {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, r)
|
||||
if w.Code != want {
|
||||
t.Fatalf("short TTL HTTP status: got %d, want %d", w.Code, want)
|
||||
}
|
||||
t.Logf("GET /api/v1/users/me: HTTP %d", w.Code)
|
||||
}
|
||||
token, _, err := sessions.CreateForUser(context.Background(), user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := sessions.User(context.Background(), token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPUser(token, 200)
|
||||
expiryStarted := time.Now()
|
||||
expiryDeadline := expiryStarted.Add(5 * time.Second)
|
||||
for {
|
||||
_, err := sessions.User(context.Background(), token)
|
||||
if errors.Is(err, services.ErrInvalidSession) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("checking expiry: %v", err)
|
||||
}
|
||||
if time.Now().After(expiryDeadline) {
|
||||
t.Fatal("session with TTL=2 seconds did not expire within 5 seconds")
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
t.Logf("SESSION_TTL_SECONDS=2: expiry observed after %s", time.Since(expiryStarted))
|
||||
assertHTTPUser(token, 401)
|
||||
token, _, err = f.sessions.CreateForUser(context.Background(), user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.sessions.Revoke(context.Background(), token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.sessions.User(context.Background(), token); err != services.ErrInvalidSession {
|
||||
t.Fatalf("revoked token: %v", err)
|
||||
}
|
||||
assertHTTPUser(token, 401)
|
||||
}
|
||||
|
||||
func TestWrongPasswordAndLogoutHTTP(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
createTestUser(t, f.users, "alice", "Алиса")
|
||||
login := func(password string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
r.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("alice:"+password)))
|
||||
w := httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
if w := login("wrong-password"); w.Code != 401 {
|
||||
t.Fatalf("wrong password returned %d", w.Code)
|
||||
}
|
||||
missingUser := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
missingUser.SetBasicAuth("missing_user", "lab2-test-password")
|
||||
missingUserResponse := httptest.NewRecorder()
|
||||
f.router.ServeHTTP(missingUserResponse, missingUser)
|
||||
if missingUserResponse.Code != 401 {
|
||||
t.Fatalf("unknown username returned %d", missingUserResponse.Code)
|
||||
}
|
||||
w := login("lab2-test-password")
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("valid login returned %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var result struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/v1/chats/not-a-uuid/messages", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+result.Token)
|
||||
w = httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("invalid chat UUID returned %d", w.Code)
|
||||
}
|
||||
r = httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+result.Token)
|
||||
w = httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
if w.Code != 204 {
|
||||
t.Fatalf("logout returned %d", w.Code)
|
||||
}
|
||||
r = httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+result.Token)
|
||||
w = httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
if w.Code != 401 {
|
||||
t.Fatalf("revoked token returned %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDependencyFailuresReturnUnavailable(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Алиса")
|
||||
failedRedis := repositories.NewRedisClient("127.0.0.1:1")
|
||||
defer failedRedis.Close()
|
||||
failedSessions := repositories.NewSessionStore(failedRedis, "unreachable:")
|
||||
redisRouter := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(f.db), failedSessions), services.NewUserService(f.users), services.NewSessionService(services.NewUserService(f.users), failedSessions, time.Hour), services.NewChatService(f.chats), services.NewMessageService(f.messages))
|
||||
assertStatus := func(router http.Handler, method, path, auth string, want int) {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
if auth != "" {
|
||||
r.Header.Set("Authorization", auth)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, r)
|
||||
if w.Code != want {
|
||||
t.Fatalf("%s %s returned %d, want %d: %s", method, path, w.Code, want, w.Body.String())
|
||||
}
|
||||
}
|
||||
assertStatus(redisRouter, "GET", "/health/ready", "", 503)
|
||||
assertStatus(redisRouter, "GET", "/api/v1/users/me", "Bearer opaque-token", 503)
|
||||
assertStatus(redisRouter, "POST", "/api/v1/auth/sessions", "Basic "+base64.StdEncoding.EncodeToString([]byte("alice:lab2-test-password")), 503)
|
||||
|
||||
pool, err := pgxpool.New(context.Background(), os.Getenv("TEST_DATABASE_URL"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool.Close()
|
||||
userStore := repositories.NewUserStore(pool)
|
||||
dbRouter := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(pool), f.sessionStore), services.NewUserService(userStore), services.NewSessionService(services.NewUserService(userStore), f.sessionStore, time.Hour), services.NewChatService(repositories.NewChatStore(pool)), services.NewMessageService(repositories.NewMessageStore(pool)))
|
||||
token, _, err := f.sessions.CreateForUser(context.Background(), user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertStatus(dbRouter, "GET", "/health/ready", "", 503)
|
||||
assertStatus(dbRouter, "GET", "/api/v1/users/me", "Bearer "+token, 503)
|
||||
assertStatus(dbRouter, "GET", "/api/v1/users/me", "", 401)
|
||||
}
|
||||
|
||||
func TestHistoryQueryPlanAtTenThousandMessages(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Алиса")
|
||||
chat := createTestChat(t, f.chats, "plan-check", []string{user.ID})
|
||||
ctx := context.Background()
|
||||
_, err := f.db.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
SELECT gen_random_uuid(),$1,$2,'plan message','2026-01-01'::timestamptz + n * interval '1 microsecond'
|
||||
FROM generate_series(1,10000) AS n`, chat.ID, user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.db.Exec(ctx, "ANALYZE messages"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var lateTime time.Time
|
||||
var lateID string
|
||||
if err := f.db.QueryRow(ctx, "SELECT created_at,id FROM messages WHERE chat_id=$1 ORDER BY created_at,id OFFSET 9000 LIMIT 1", chat.ID).Scan(&lateTime, &lateID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
at time.Time
|
||||
id string
|
||||
}{
|
||||
{"first", time.Time{}, "00000000-0000-0000-0000-000000000000"},
|
||||
{"late", lateTime, lateID},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var plan []byte
|
||||
err := f.db.QueryRow(ctx, `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
||||
SELECT id,chat_id,sender_id,text,created_at FROM messages
|
||||
WHERE chat_id=$1 AND (created_at,id)>($2,$3::uuid)
|
||||
ORDER BY created_at,id LIMIT $4`, chat.ID, tc.at, tc.id, 51).Scan(&plan)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Contains(plan, []byte("messages_history_idx")) || bytes.Contains(plan, []byte(`"Node Type": "Seq Scan"`)) {
|
||||
t.Fatalf("history page did not use the index: %s", plan)
|
||||
}
|
||||
t.Logf("%s page EXPLAIN (ANALYZE, BUFFERS): %s", tc.name, plan)
|
||||
})
|
||||
}
|
||||
var count int
|
||||
if err := f.db.QueryRow(ctx, "SELECT count(*) FROM messages WHERE chat_id=$1", chat.ID).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count < 10000 {
|
||||
t.Fatal(fmt.Errorf("history contains only %d messages", count))
|
||||
}
|
||||
}
|
||||
@@ -17,20 +17,22 @@ import (
|
||||
)
|
||||
|
||||
type testFixture struct {
|
||||
db *pgxpool.Pool
|
||||
users *repositories.UserStore
|
||||
chats *repositories.ChatStore
|
||||
messages *repositories.MessageStore
|
||||
sessions *services.SessionService
|
||||
router http.Handler
|
||||
db *pgxpool.Pool
|
||||
users *repositories.UserStore
|
||||
chats *repositories.ChatStore
|
||||
messages *repositories.MessageStore
|
||||
sessionStore *repositories.SessionStore
|
||||
sessions *services.SessionService
|
||||
router http.Handler
|
||||
}
|
||||
|
||||
// Each test owns a new schema; public application tables are never modified.
|
||||
func newTestFixture(t *testing.T) *testFixture {
|
||||
t.Helper()
|
||||
url := os.Getenv("TEST_DATABASE_URL")
|
||||
if url == "" {
|
||||
t.Skip("PostgreSQL tests: run make test-backend, or set TEST_DATABASE_URL")
|
||||
redisAddress := os.Getenv("TEST_REDIS_ADDR")
|
||||
if url == "" || redisAddress == "" {
|
||||
t.Skip("integration tests: run make test-backend, or set TEST_DATABASE_URL and TEST_REDIS_ADDR")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
@@ -68,13 +70,26 @@ func newTestFixture(t *testing.T) *testFixture {
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ddl, err = os.ReadFile("../repositories/migrations/000002_redis_sessions.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
redisClient := repositories.NewRedisClient(redisAddress)
|
||||
t.Cleanup(func() { _ = redisClient.Close() })
|
||||
if err := redisClient.Ping(ctx).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
users := repositories.NewUserStore(db)
|
||||
chats := repositories.NewChatStore(db)
|
||||
messages := repositories.NewMessageStore(db)
|
||||
userService := services.NewUserService(users)
|
||||
sessions := services.NewSessionService(userService, repositories.NewSessionStore(db), time.Hour)
|
||||
router := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db)), userService, sessions, services.NewChatService(chats), services.NewMessageService(messages))
|
||||
return &testFixture{db, users, chats, messages, sessions, router}
|
||||
sessionStore := repositories.NewSessionStore(redisClient, "test:"+schema+":session:")
|
||||
sessions := services.NewSessionService(userService, sessionStore, time.Hour)
|
||||
router := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db), sessionStore), userService, sessions, services.NewChatService(chats), services.NewMessageService(messages))
|
||||
return &testFixture{db: db, users: users, chats: chats, messages: messages, sessionStore: sessionStore, sessions: sessions, router: router}
|
||||
}
|
||||
|
||||
func createTestUser(t *testing.T, store *repositories.UserStore, username, name string) (repositories.User, bool) {
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client
|
||||
|
||||
CRITERIA = (
|
||||
("01-smoke", "Публичный smoke и API"),
|
||||
("02-postgresql-schema", "Чистая схема PostgreSQL, ключи и индексы"),
|
||||
("03-chat-atomicity", "Атомарное создание чата"),
|
||||
("04-authentication", "Argon2id, Basic, Bearer, TTL и logout"),
|
||||
("05-session-persistence", "Сохранность данных и Redis-сессии"),
|
||||
("06-migrations", "Повторное применение и откат миграций"),
|
||||
("07-compose-secrets", "Стенд, тома и исключение секретов из Git"),
|
||||
("08-code-checks", "Проверки кода и race detector"),
|
||||
("09-resource-limits", "Пулы, таймауты и параметризованные SQL"),
|
||||
("10-dependency-failures", "Отказ Redis и PostgreSQL"),
|
||||
("11-history-10000", "План истории на 10 000 сообщений"),
|
||||
("12-track2-dataset", "Трек 2: объём и распределение истории"),
|
||||
("13-track2-indexes", "Трек 2: чтение и стоимость записи"),
|
||||
("14-track2-recovery", "Трек 2: backup и восстановление"),
|
||||
)
|
||||
|
||||
|
||||
def block(language, value):
|
||||
return f"\n```{language}\n{value.rstrip()}\n```\n"
|
||||
|
||||
|
||||
class Collector:
|
||||
"""Shared command execution, document writing and Compose configuration."""
|
||||
|
||||
def __init__(self, args):
|
||||
self.args = args
|
||||
self.env = dict(os.environ, COMPOSE_FILE=f"compose.yaml:{args.compose_override}",
|
||||
COMPOSE_PROJECT_NAME=args.project)
|
||||
self.compose = ["docker", "compose", "--env-file", ".env"]
|
||||
self.track_compose = ["docker", "compose", "-f", "compose.track2.yaml",
|
||||
"-p", f"messenger-track2-{args.track_run}"]
|
||||
self.outdir = ROOT / "evidence/criteria"
|
||||
self.track = ROOT / "evidence/track2" / args.track_run
|
||||
self.test_output = ""
|
||||
self.docs = {}
|
||||
self.outdir.mkdir(parents=True, exist_ok=True)
|
||||
now = dt.datetime.now(dt.timezone.utc).isoformat()
|
||||
for key, title in CRITERIA:
|
||||
path = self.outdir / f"{key}.md"
|
||||
if args.resume_after_migrations and path.exists():
|
||||
self.docs[key] = path.read_text()
|
||||
else:
|
||||
self.docs[key] = (
|
||||
f"# {title}\n\nДата сбора: `{now}`.\n\n"
|
||||
"Команды выполняются в корне репозитория, Linux/WSL. "
|
||||
f"Контекст Compose: `COMPOSE_PROJECT_NAME={args.project}`, "
|
||||
f"`COMPOSE_FILE={self.env['COMPOSE_FILE']}`. "
|
||||
"Параметры стенда и запуск: [07-compose-secrets.md](07-compose-secrets.md).\n"
|
||||
)
|
||||
|
||||
def append(self, key, value):
|
||||
self.docs[key] += "\n" + value
|
||||
(self.outdir / f"{key}.md").write_text(self.docs[key], encoding="utf-8")
|
||||
|
||||
def reference(self, key, path, label=None):
|
||||
target = ROOT / path
|
||||
if not target.is_file():
|
||||
raise FileNotFoundError(target)
|
||||
relative = os.path.relpath(target, self.outdir).replace(os.sep, "/")
|
||||
self.append(key, f"Файл: [{label or path}]({relative}).\n")
|
||||
|
||||
def run(self, key, argv, input=None):
|
||||
result = subprocess.run(argv, cwd=ROOT, env=self.env, input=input, text=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False)
|
||||
content = "### Команда\n" + block("sh", shlex.join(argv))
|
||||
if input is not None:
|
||||
content += "\n### SQL, переданный на stdin\n" + block("sql", input)
|
||||
content += "\n### Фактический вывод\n" + block("text", result.stdout or "(вывода нет)")
|
||||
content += f"\nКод завершения: `{result.returncode}`.\n"
|
||||
self.append(key, content)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"{shlex.join(argv)}: exit={result.returncode}")
|
||||
print(f"{key}: {shlex.join(argv[:4])} exit=0", flush=True)
|
||||
return result.stdout
|
||||
|
||||
def sql(self, key, query, database=None):
|
||||
database_arg = shlex.quote(database) if database else '"$POSTGRES_DB"'
|
||||
return self.run(key, self.compose + ["exec", "-T", "db", "sh", "-c",
|
||||
f'exec psql -X -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d {database_arg}'], input=query)
|
||||
|
||||
def track_sql(self, key, query, service="restore"):
|
||||
return self.run(key, self.track_compose + ["exec", "-T", service, "psql", "-X",
|
||||
"-v", "ON_ERROR_STOP=1", "-U", "track2", "-d", "messenger_track2"], input=query)
|
||||
|
||||
def test_excerpt(self, key, names, path):
|
||||
selected = []
|
||||
include = False
|
||||
for line in self.test_output.splitlines():
|
||||
if line.startswith("=== RUN"):
|
||||
include = any(name in line for name in names)
|
||||
if include:
|
||||
selected.append(line)
|
||||
if not selected:
|
||||
raise ValueError(f"No test output for {key}: {names}")
|
||||
self.append(key, "### Выполненная команда\n" + block("sh", "make test-backend") +
|
||||
"\nФрагмент фактического вывода полного запуска "
|
||||
"[08-code-checks.md](08-code-checks.md); тесты не запускались выборочно.\n" +
|
||||
block("text", "\n".join(selected)) + "\nКод завершения полного запуска: `0`.\n")
|
||||
self.reference(key, path)
|
||||
|
||||
def recorded_experiment(self, key):
|
||||
self.append(key, "### Ранее выполненный эксперимент\n" +
|
||||
block("sh", f"make track2-run RUN_ID={self.args.track_run}"))
|
||||
output_path = self.track / "run-output.txt"
|
||||
if output_path.exists():
|
||||
output = output_path.read_text()
|
||||
if f"messenger-track2-{self.args.track_run};" not in output:
|
||||
raise ValueError("Recorded experiment stdout does not match --track-run")
|
||||
self.append(key, "Сохранённый stdout завершённого прогона "
|
||||
"(локальный путь архива опущен):\n" + block("text", output))
|
||||
else:
|
||||
journal = [json.loads(line) for line in
|
||||
(self.track / "commands.jsonl").read_text().splitlines()]
|
||||
if not journal or any(item["exit_code"] != 0 for item in journal):
|
||||
raise ValueError("Recorded experiment command journal is empty or contains failures")
|
||||
self.append(key, "Команды и фактические коды завершения сохранены в журнале прогона.")
|
||||
self.reference(key, "src/experiments/track2/run.py")
|
||||
self.reference(key, str(self.track.relative_to(ROOT) / "commands.jsonl"))
|
||||
|
||||
def recorded_json(self, key, name):
|
||||
self.append(key, f"### Сохранённый результат: `{name}`\n" +
|
||||
block("json", (self.track / name).read_text()))
|
||||
|
||||
|
||||
def collect_smoke(c):
|
||||
c.run("01-smoke", ["make", "test", f"BASE_URL={c.args.base_url}"])
|
||||
c.append("01-smoke", "### Проверка API через прокси frontend\n")
|
||||
c.run("01-smoke", ["make", "test", f"BASE_URL={c.args.frontend_url}"])
|
||||
c.reference("01-smoke", "tests/smoke.py")
|
||||
|
||||
|
||||
def collect_postgresql_schema(c):
|
||||
c.sql("02-postgresql-schema", """SELECT version, dirty FROM schema_migrations;
|
||||
SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename;
|
||||
SELECT table_name, column_name, data_type FROM information_schema.columns
|
||||
WHERE table_schema='public' ORDER BY table_name, ordinal_position;
|
||||
SELECT conrelid::regclass AS table_name, conname, pg_get_constraintdef(oid)
|
||||
FROM pg_constraint WHERE connamespace='public'::regnamespace ORDER BY 1,2;
|
||||
SELECT tablename,indexname,indexdef FROM pg_indexes WHERE schemaname='public' ORDER BY 1,2;
|
||||
SELECT (SELECT count(*) FROM users) AS users, (SELECT count(*) FROM chats) AS chats,
|
||||
(SELECT count(*) FROM chat_members) AS members, (SELECT count(*) FROM messages) AS messages;
|
||||
""")
|
||||
|
||||
|
||||
def collect_chat_atomicity(c):
|
||||
c.test_excerpt("03-chat-atomicity", ["TestChatTransactionRollsBackAfterMemberInsertFailure",
|
||||
"TestConcurrentRegistrationSameUsername"], "src/backend/tests/grade4_test.go")
|
||||
|
||||
|
||||
def collect_authentication(c):
|
||||
key = "04-authentication"
|
||||
c.test_excerpt(key, ["TestShortSessionTTLAndLogout", "TestWrongPasswordAndLogoutHTTP"],
|
||||
"src/backend/tests/grade4_test.go")
|
||||
c.test_excerpt(key, ["TestStoredPasswordUsesArgon2id", "TestPasswordKDFUsesSaltAndFullUTF8Password",
|
||||
"TestBearerRequiredIgnoresXUserID"], "src/backend/tests/security_test.go")
|
||||
c.append(key, "Basic и Bearer через HTTP также проверены "
|
||||
"публичным сценарием: [01-smoke.md](01-smoke.md).")
|
||||
|
||||
|
||||
def collect_session_persistence(c):
|
||||
key = "05-session-persistence"
|
||||
c.reference(key, "scripts/restart.sh")
|
||||
c.run(key, c.compose + ["exec", "-T", "redis", "redis-cli", "CONFIG", "GET",
|
||||
"appendonly", "appendfsync"])
|
||||
c.run(key, ["make", "test-persistence", f"BASE_URL={c.args.base_url}",
|
||||
"ACTION_SCRIPT=scripts/restart.sh"])
|
||||
c.run(key, c.compose + ["ps"])
|
||||
|
||||
|
||||
def collect_migrations(c):
|
||||
key = "06-migrations"
|
||||
database = "evidence_migrations"
|
||||
c.sql(key, f"CREATE DATABASE {database};")
|
||||
for direction in ("up", "up", "down", "up"):
|
||||
c.run(key, c.compose + ["run", "--rm", "--no-deps", "--entrypoint", "/bin/sh",
|
||||
"api", "-c", 'DATABASE_URL="${DATABASE_URL%/*}/' + database +
|
||||
'?sslmode=disable" ./messenger migrate ' + direction])
|
||||
query = "SELECT version,dirty FROM schema_migrations;"
|
||||
query += (" SELECT count(*) FROM sessions;" if direction == "down" else
|
||||
" SELECT to_regclass('public.sessions');")
|
||||
c.sql(key, query, database)
|
||||
|
||||
|
||||
def collect_compose_secrets(c):
|
||||
key = "07-compose-secrets"
|
||||
if c.args.resume_after_migrations:
|
||||
c.run(key, c.compose + ["up", "-d", "--wait"])
|
||||
return
|
||||
volumes = ["docker", "volume", "ls", "--filter",
|
||||
f"label=com.docker.compose.project={c.args.project}"]
|
||||
if c.run(key, volumes + ["-q"]).strip():
|
||||
raise RuntimeError("Use a new project name: existing volumes detected")
|
||||
c.append(key, "### Окружение\n" + block("sh",
|
||||
f"export COMPOSE_PROJECT_NAME={c.args.project}\n"
|
||||
f"export COMPOSE_FILE={c.env['COMPOSE_FILE']}"))
|
||||
c.reference(key, c.args.compose_override)
|
||||
c.reference(key, "compose.yaml")
|
||||
c.run(key, c.compose + ["config", "--quiet"])
|
||||
c.run(key, ["git", "check-ignore", ".env"])
|
||||
c.run(key, ["git", "ls-files", ".env"])
|
||||
c.run(key, ["make", "app-up"])
|
||||
c.run(key, c.compose + ["ps"])
|
||||
c.run(key, volumes)
|
||||
|
||||
|
||||
def collect_code_checks(c):
|
||||
key = "08-code-checks"
|
||||
c.run(key, ["make", "check"])
|
||||
c.test_output = c.run(key, ["make", "test-backend"])
|
||||
c.run(key, c.compose + ["run", "--rm", "--no-deps", "backend-tests",
|
||||
"go", "vet", "./src/backend/..."])
|
||||
c.run(key, c.compose + ["exec", "-T", "frontend", "npm", "run", "build"])
|
||||
|
||||
|
||||
def collect_resource_limits(c):
|
||||
key = "09-resource-limits"
|
||||
search = ["rg", "-n"] if shutil.which("rg") else ["grep", "-nE"]
|
||||
c.run(key, search + [
|
||||
("MaxConns|ConnectTimeout|queryTimeout|PoolSize|DialTimeout|ReadTimeout|"
|
||||
"WriteTimeout|ReadHeaderTimeout|IdleTimeout|MaxRetries"),
|
||||
"src/backend/repositories/database.go", "src/backend/repositories/timeout.go",
|
||||
"src/backend/repositories/redis.go", "src/backend/main.go",
|
||||
])
|
||||
c.reference(key, "src/backend/repositories/message.go")
|
||||
c.append(key, "Тесты отказов и их полный вывод: [08-code-checks.md](08-code-checks.md).")
|
||||
|
||||
|
||||
def collect_dependency_failures(c):
|
||||
key = "10-dependency-failures"
|
||||
c.reference(key, "src/experiments/evidence/collect.py", "Сценарий collect_dependency_failures")
|
||||
client = Client(c.args.base_url)
|
||||
alice, _, _, _ = client.bootstrap()
|
||||
|
||||
def check_http(path, expected, actor=None):
|
||||
response = client.call("GET", path, expected, actor=actor)
|
||||
auth = "Bearer" if actor else "anonymous"
|
||||
c.append(key, block("text", f"GET {path} [{auth}] -> HTTP {response['status']}"))
|
||||
|
||||
check_http("/health/ready", 200)
|
||||
check_http("/api/v1/users/me", 200, alice)
|
||||
for dependency in ("redis", "db"):
|
||||
c.run(key, c.compose + ["stop", dependency])
|
||||
try:
|
||||
check_http("/health/ready", 503)
|
||||
check_http("/api/v1/users/me", 503, alice)
|
||||
check_http("/api/v1/users/me", 401)
|
||||
finally:
|
||||
c.run(key, c.compose + ["up", "-d", "--wait", dependency])
|
||||
check_http("/health/ready", 200)
|
||||
check_http("/api/v1/users/me", 200, alice)
|
||||
c.append(key, "PASS: обе зависимости восстановлены; "
|
||||
"в проверках до и после остановки использован один и тот же токен.")
|
||||
|
||||
|
||||
def collect_history_10000(c):
|
||||
c.test_excerpt("11-history-10000", ["TestHistoryQueryPlanAtTenThousandMessages"],
|
||||
"src/backend/tests/grade4_test.go")
|
||||
|
||||
|
||||
def collect_track2_dataset(c):
|
||||
key = "12-track2-dataset"
|
||||
c.recorded_experiment(key)
|
||||
c.reference(key, "src/experiments/track2/seed.sql")
|
||||
c.track_sql(key, """SELECT count(*) AS total FROM messages;
|
||||
SELECT chat_id,count(*) FROM messages GROUP BY chat_id ORDER BY chat_id;
|
||||
""")
|
||||
|
||||
|
||||
def collect_track2_indexes(c):
|
||||
key = "13-track2-indexes"
|
||||
c.recorded_experiment(key)
|
||||
c.reference(key, str(c.track.relative_to(ROOT) / "queries.sql"))
|
||||
for name in ("reads.json", "writes.json", "sizes.json", "read-base-large-late.json",
|
||||
"read-base-large-offset.json", "read-covering-large-late.json", "write-base.json"):
|
||||
c.recorded_json(key, name)
|
||||
|
||||
|
||||
def collect_track2_recovery(c):
|
||||
key = "14-track2-recovery"
|
||||
c.recorded_experiment(key)
|
||||
journal = [json.loads(line) for line in (c.track / "commands.jsonl").read_text().splitlines()]
|
||||
commands = [item for item in journal if any(
|
||||
arg in ("pg_dump", "pg_restore", "restore") for arg in item["command"])]
|
||||
c.append(key, "### Команды dump/restore и запуска нового хранилища из журнала\n" +
|
||||
block("json", json.dumps(commands, ensure_ascii=False, indent=2)))
|
||||
for name in ("recovery.json", "first-query.json"):
|
||||
c.recorded_json(key, name)
|
||||
for service in ("source", "restore"):
|
||||
c.track_sql(key, """SELECT count(*) AS messages FROM messages;
|
||||
SELECT count(*) AS post_backup_marker FROM messages
|
||||
WHERE id='33333333-3333-4333-8333-333333333333';
|
||||
""", service)
|
||||
c.run(key, ["python3", "-c",
|
||||
"import json; from pathlib import Path; "
|
||||
f"r=json.loads(Path({str(c.track.relative_to(ROOT) / 'recovery.json')!r}).read_text()); "
|
||||
"assert r['expected'] == r['actual']; "
|
||||
"assert r['marker_source'] == 1 and r['marker_restore'] == 0; "
|
||||
"print('PASS: counts, distribution, nine samples and post-backup marker')"])
|
||||
|
||||
|
||||
def update_report():
|
||||
report = ROOT / "REPORT.md"
|
||||
rows = report.read_text().splitlines()
|
||||
index = 0
|
||||
in_criteria = False
|
||||
for i, row in enumerate(rows):
|
||||
if row.startswith(("| Критерий README |", "| Критерий трека 2 |")):
|
||||
in_criteria = True
|
||||
continue
|
||||
if not row.startswith("|"):
|
||||
in_criteria = False
|
||||
if in_criteria and row.startswith("| ") and len(row.split("|")) == 6:
|
||||
cells = row.split("|")
|
||||
if cells[1].strip() != "---":
|
||||
key, title = CRITERIA[index]
|
||||
cells[4] = f" [{title}](evidence/criteria/{key}.md) "
|
||||
rows[i] = "|".join(cells)
|
||||
index += 1
|
||||
if index != len(CRITERIA):
|
||||
raise ValueError(f"Expected {len(CRITERIA)} criteria, found {index}")
|
||||
report.write_text("\n".join(rows) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--project", required=True)
|
||||
parser.add_argument("--base-url", default="http://localhost:18080")
|
||||
parser.add_argument("--frontend-url", default="http://localhost:15173")
|
||||
parser.add_argument("--compose-override", default="src/experiments/evidence/compose.override.yaml")
|
||||
parser.add_argument("--track-run", default="20261001-c")
|
||||
parser.add_argument("--resume-after-migrations", action="store_true",
|
||||
help="Continue an interrupted collection after successful migrations")
|
||||
args = parser.parse_args()
|
||||
if not re.fullmatch(r"messenger-evidence-[a-z0-9-]+", args.project):
|
||||
parser.error("project must start with messenger-evidence-")
|
||||
c = Collector(args)
|
||||
collect_compose_secrets(c)
|
||||
try:
|
||||
if not args.resume_after_migrations:
|
||||
collect_postgresql_schema(c)
|
||||
collect_smoke(c)
|
||||
collect_code_checks(c)
|
||||
collect_chat_atomicity(c)
|
||||
collect_authentication(c)
|
||||
collect_history_10000(c)
|
||||
collect_session_persistence(c)
|
||||
collect_migrations(c)
|
||||
collect_resource_limits(c)
|
||||
collect_dependency_failures(c)
|
||||
finally:
|
||||
c.run("07-compose-secrets", c.compose + ["down"])
|
||||
collect_track2_dataset(c)
|
||||
collect_track2_indexes(c)
|
||||
collect_track2_recovery(c)
|
||||
update_report()
|
||||
print("PASS: 14 separate criterion documents; REPORT evidence links updated", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
services:
|
||||
api:
|
||||
ports: !override
|
||||
- "127.0.0.1:18080:8080"
|
||||
frontend:
|
||||
ports: !override
|
||||
- "127.0.0.1:15173:5173"
|
||||
@@ -0,0 +1,399 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
CHATS = [
|
||||
("large", "22222222-2222-4222-8222-222222222221", 100000),
|
||||
("medium", "22222222-2222-4222-8222-222222222222", 15000),
|
||||
("small", "22222222-2222-4222-8222-222222222223", 5000),
|
||||
]
|
||||
USER = "11111111-1111-4111-8111-111111111111"
|
||||
MARKER = "33333333-3333-4333-8333-333333333333"
|
||||
EVENT_LOG = None
|
||||
|
||||
|
||||
def command(args, data=None):
|
||||
started = time.perf_counter()
|
||||
result = subprocess.run(
|
||||
args, check=False, cwd=ROOT, input=data, capture_output=True
|
||||
)
|
||||
if EVENT_LOG:
|
||||
with EVENT_LOG.open("a", encoding="utf-8") as stream:
|
||||
stream.write(
|
||||
json.dumps(
|
||||
{
|
||||
"utc": datetime.now(timezone.utc).isoformat(),
|
||||
"command": args,
|
||||
"seconds": time.perf_counter() - started,
|
||||
"exit_code": result.returncode,
|
||||
}
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stderr.decode(errors="replace"))
|
||||
return result.stdout
|
||||
|
||||
|
||||
def main():
|
||||
global EVENT_LOG
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=["run", "status", "stop", "clean"])
|
||||
parser.add_argument("--run-id", required=True)
|
||||
args = parser.parse_args()
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,39}", args.run_id):
|
||||
parser.error("RUN_ID must contain 1-40 lowercase letters, digits or hyphens")
|
||||
project = "messenger-track2-" + args.run_id
|
||||
compose = ["docker", "compose", "-f", "compose.track2.yaml", "-p", project]
|
||||
output = ROOT / "backups" / "track2" / args.run_id
|
||||
if args.action != "run":
|
||||
action = {
|
||||
"status": ["ps", "-a"],
|
||||
"stop": ["stop"],
|
||||
"clean": ["down", "--volumes"],
|
||||
}[args.action]
|
||||
print(command(compose + action).decode())
|
||||
return
|
||||
# Never reuse an existing project, volume or output directory.
|
||||
volumes = command(
|
||||
[
|
||||
"docker",
|
||||
"volume",
|
||||
"ls",
|
||||
"-q",
|
||||
"--filter",
|
||||
"label=com.docker.compose.project=" + project,
|
||||
]
|
||||
).strip()
|
||||
containers = command(
|
||||
[
|
||||
"docker",
|
||||
"ps",
|
||||
"-aq",
|
||||
"--filter",
|
||||
"label=com.docker.compose.project=" + project,
|
||||
]
|
||||
).strip()
|
||||
if output.exists() or volumes or containers:
|
||||
parser.error("RUN_ID already exists; use a new RUN_ID (archives are retained)")
|
||||
output.mkdir(parents=True)
|
||||
EVENT_LOG = output / "commands.jsonl"
|
||||
(output / "protocol-before-run.md").write_bytes(
|
||||
(ROOT / "evidence" / "track2.md").read_bytes()
|
||||
)
|
||||
|
||||
def save(name, value):
|
||||
(output / name).write_text(
|
||||
json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
def sql(query, service="source"):
|
||||
return (
|
||||
command(
|
||||
compose
|
||||
+ [
|
||||
"exec",
|
||||
"-T",
|
||||
service,
|
||||
"psql",
|
||||
"-X",
|
||||
"-qAt",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-U",
|
||||
"track2",
|
||||
"-d",
|
||||
"messenger_track2",
|
||||
],
|
||||
query.encode(),
|
||||
)
|
||||
.decode()
|
||||
.strip()
|
||||
)
|
||||
|
||||
statements = []
|
||||
|
||||
def explain(query, name, wal=False):
|
||||
statements.append("-- " + name + "\n" + query + ";")
|
||||
plans = []
|
||||
for trial in range(8):
|
||||
plan = json.loads(
|
||||
sql(
|
||||
"EXPLAIN (ANALYZE, BUFFERS, "
|
||||
+ ("WAL, " if wal else "")
|
||||
+ "FORMAT JSON) "
|
||||
+ query
|
||||
)
|
||||
)[0]
|
||||
if trial:
|
||||
plans.append(plan)
|
||||
save(name + ".json", plans)
|
||||
times = [p["Execution Time"] for p in plans]
|
||||
node = plans[0]["Plan"]
|
||||
while node.get("Plans"):
|
||||
node = node["Plans"][0]
|
||||
return {
|
||||
"name": name,
|
||||
"median_ms": statistics.median(times),
|
||||
"min_ms": min(times),
|
||||
"max_ms": max(times),
|
||||
"scan": node["Node Type"],
|
||||
"index": node.get("Index Name"),
|
||||
"scan_rows": node.get("Actual Rows"),
|
||||
"heap_fetches": node.get("Heap Fetches"),
|
||||
"shared_hit": plans[0]["Plan"].get("Shared Hit Blocks", 0),
|
||||
"shared_read": plans[0]["Plan"].get("Shared Read Blocks", 0),
|
||||
}
|
||||
|
||||
print("Starting isolated source database", flush=True)
|
||||
command(compose + ["up", "-d", "--wait", "source"])
|
||||
command(compose + ["run", "--build", "--rm", "migrator"])
|
||||
sql((Path(__file__).parent / "seed.sql").read_text(encoding="utf-8"))
|
||||
manifest = {
|
||||
"started_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"run_id": args.run_id,
|
||||
"base_commit": command(["git", "rev-parse", "HEAD"]).decode().strip(),
|
||||
"dirty": bool(command(["git", "status", "--porcelain"]).strip()),
|
||||
"docker_version": command(
|
||||
["docker", "version", "--format", "{{.Server.Version}}"]
|
||||
)
|
||||
.decode()
|
||||
.strip(),
|
||||
"docker_resources": command(
|
||||
["docker", "info", "--format", "{{.NCPU}} CPUs; {{.MemTotal}} bytes RAM"]
|
||||
)
|
||||
.decode()
|
||||
.strip(),
|
||||
"postgres": sql("SELECT version()"),
|
||||
"page_size": 50,
|
||||
"warmup": 1,
|
||||
"repetitions": 7,
|
||||
"settings": json.loads(
|
||||
sql(
|
||||
"SELECT json_object_agg(name,setting) FROM pg_settings WHERE name IN ('shared_buffers','work_mem','effective_cache_size','fsync','synchronous_commit','full_page_writes','max_parallel_workers_per_gather')"
|
||||
)
|
||||
),
|
||||
"container_limits": command(
|
||||
[
|
||||
"docker",
|
||||
"inspect",
|
||||
"--format",
|
||||
"image={{.Image}} memory_limit={{.HostConfig.Memory}} nano_cpus={{.HostConfig.NanoCpus}}",
|
||||
project + "-source-1",
|
||||
]
|
||||
)
|
||||
.decode()
|
||||
.strip(),
|
||||
"source_hashes": {
|
||||
str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in [
|
||||
Path(__file__),
|
||||
Path(__file__).parent / "seed.sql",
|
||||
ROOT / "compose.track2.yaml",
|
||||
ROOT / "evidence" / "track2.md",
|
||||
]
|
||||
+ sorted((ROOT / "src/backend/repositories/migrations").glob("*.sql"))
|
||||
},
|
||||
}
|
||||
save("manifest.json", manifest)
|
||||
reads = []
|
||||
sizes = {}
|
||||
for variant in ["base", "covering"]:
|
||||
if variant == "covering":
|
||||
sql(
|
||||
"DROP INDEX messages_history_idx; CREATE INDEX messages_history_covering_idx ON messages(chat_id,created_at,id) INCLUDE(sender_id,text)"
|
||||
)
|
||||
sql("VACUUM (ANALYZE) messages")
|
||||
sizes[variant] = json.loads(
|
||||
sql(
|
||||
"SELECT json_build_object('table_bytes',pg_relation_size('messages'),'index_bytes',pg_relation_size('"
|
||||
+ (
|
||||
"messages_history_idx"
|
||||
if variant == "base"
|
||||
else "messages_history_covering_idx"
|
||||
)
|
||||
+ "'))"
|
||||
)
|
||||
)
|
||||
for label, chat, count in CHATS:
|
||||
depth = int(count * 0.9)
|
||||
cursor = sql(
|
||||
f"SELECT created_at::text || '|' || id::text FROM messages WHERE chat_id='{chat}' ORDER BY created_at,id OFFSET {depth - 1} LIMIT 1"
|
||||
)
|
||||
stamp, identity = cursor.split("|")
|
||||
select = f"SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id='{chat}'"
|
||||
first = (
|
||||
select
|
||||
+ " AND (created_at,id)>('0001-01-01'::timestamptz,'00000000-0000-0000-0000-000000000000'::uuid) ORDER BY created_at,id LIMIT 50"
|
||||
)
|
||||
late = (
|
||||
select
|
||||
+ f" AND (created_at,id)>('{stamp}'::timestamptz,'{identity}'::uuid) ORDER BY created_at,id LIMIT 50"
|
||||
)
|
||||
offset = select + f" ORDER BY created_at,id OFFSET {depth} LIMIT 50"
|
||||
if sql(late) != sql(offset):
|
||||
raise RuntimeError("Cursor and OFFSET results differ")
|
||||
for kind, query in [("first", first), ("late", late), ("offset", offset)]:
|
||||
reads.append(explain(query, f"read-{variant}-{label}-{kind}"))
|
||||
print("Read measurements complete: " + variant, flush=True)
|
||||
sql(
|
||||
"DROP INDEX messages_history_covering_idx; CREATE INDEX messages_history_idx ON messages(chat_id,created_at,id)"
|
||||
)
|
||||
writes = []
|
||||
sql(
|
||||
"CREATE TABLE write_input AS SELECT * FROM messages ORDER BY chat_id,created_at,id LIMIT 10000"
|
||||
)
|
||||
for variant in ["none", "base", "covering"]:
|
||||
sql(
|
||||
"CREATE TABLE write_bench (LIKE messages INCLUDING CONSTRAINTS); ALTER TABLE write_bench ADD PRIMARY KEY(id)"
|
||||
)
|
||||
if variant != "none":
|
||||
sql(
|
||||
"CREATE INDEX write_history_idx ON write_bench(chat_id,created_at,id)"
|
||||
+ (" INCLUDE(sender_id,text)" if variant == "covering" else "")
|
||||
)
|
||||
plans = []
|
||||
query = "INSERT INTO write_bench SELECT * FROM write_input ORDER BY chat_id,created_at,id"
|
||||
statements.append(
|
||||
"-- write-" + variant + " (TRUNCATE before each trial)\n" + query + ";"
|
||||
)
|
||||
for trial in range(8):
|
||||
sql("TRUNCATE write_bench")
|
||||
plan = json.loads(
|
||||
sql("EXPLAIN (ANALYZE, BUFFERS, WAL, FORMAT JSON) " + query)
|
||||
)[0]
|
||||
if trial:
|
||||
plans.append(plan)
|
||||
save("write-" + variant + ".json", plans)
|
||||
times = [p["Execution Time"] for p in plans]
|
||||
writes.append(
|
||||
{
|
||||
"variant": variant,
|
||||
"median_ms": statistics.median(times),
|
||||
"min_ms": min(times),
|
||||
"max_ms": max(times),
|
||||
"median_wal_bytes": statistics.median(
|
||||
p["Plan"]["WAL Bytes"] for p in plans
|
||||
),
|
||||
"index_bytes": int(sql("SELECT pg_indexes_size('write_bench')")),
|
||||
}
|
||||
)
|
||||
sql("DROP TABLE write_bench")
|
||||
sql("DROP TABLE write_input")
|
||||
save("reads.json", reads)
|
||||
save("writes.json", writes)
|
||||
save("sizes.json", sizes)
|
||||
(output / "queries.sql").write_text(
|
||||
"\n\n".join(statements) + "\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
def snapshot(service):
|
||||
counts = {
|
||||
table: int(sql("SELECT count(*) FROM " + table, service))
|
||||
for table in [
|
||||
"users",
|
||||
"chats",
|
||||
"chat_members",
|
||||
"messages",
|
||||
"schema_migrations",
|
||||
]
|
||||
}
|
||||
distribution = sql(
|
||||
"SELECT chat_id,count(*) FROM messages GROUP BY chat_id ORDER BY chat_id",
|
||||
service,
|
||||
)
|
||||
samples = []
|
||||
for _, chat, count in CHATS:
|
||||
for position in [0, count // 2, count - 1]:
|
||||
samples.append(
|
||||
sql(
|
||||
f"SELECT row_to_json(m) FROM (SELECT * FROM messages WHERE chat_id='{chat}' ORDER BY created_at,id OFFSET {position} LIMIT 1) m",
|
||||
service,
|
||||
)
|
||||
)
|
||||
return {"counts": counts, "distribution": distribution, "samples": samples}
|
||||
|
||||
expected = snapshot("source")
|
||||
print("Creating backup and restoring into a new volume", flush=True)
|
||||
started = time.perf_counter()
|
||||
dump = command(
|
||||
compose
|
||||
+ [
|
||||
"exec",
|
||||
"-T",
|
||||
"source",
|
||||
"pg_dump",
|
||||
"-U",
|
||||
"track2",
|
||||
"-d",
|
||||
"messenger_track2",
|
||||
"-Fc",
|
||||
]
|
||||
)
|
||||
dump_seconds = time.perf_counter() - started
|
||||
(output / "messenger.dump").write_bytes(dump)
|
||||
sql(
|
||||
f"INSERT INTO messages VALUES ('{MARKER}','{CHATS[0][1]}','{USER}','After backup marker','2026-01-02')"
|
||||
)
|
||||
available_started = time.perf_counter()
|
||||
command(compose + ["up", "-d", "--wait", "restore"])
|
||||
restore_started = time.perf_counter()
|
||||
command(
|
||||
compose
|
||||
+ [
|
||||
"exec",
|
||||
"-T",
|
||||
"restore",
|
||||
"pg_restore",
|
||||
"--exit-on-error",
|
||||
"--no-owner",
|
||||
"--no-acl",
|
||||
"-U",
|
||||
"track2",
|
||||
"-d",
|
||||
"messenger_track2",
|
||||
],
|
||||
dump,
|
||||
)
|
||||
restore_seconds = time.perf_counter() - restore_started
|
||||
actual = snapshot("restore")
|
||||
if expected != actual:
|
||||
raise RuntimeError("Restored snapshot differs")
|
||||
if (
|
||||
sql(f"SELECT count(*) FROM messages WHERE id='{MARKER}'") != "1"
|
||||
or sql(f"SELECT count(*) FROM messages WHERE id='{MARKER}'", "restore") != "0"
|
||||
):
|
||||
raise RuntimeError("Post-backup marker check failed")
|
||||
recovery = {
|
||||
"dump_seconds": dump_seconds,
|
||||
"dump_bytes": len(dump),
|
||||
"dump_sha256": hashlib.sha256(dump).hexdigest(),
|
||||
"restore_seconds": restore_seconds,
|
||||
"startup_restore_verify_seconds": time.perf_counter() - available_started,
|
||||
"expected": expected,
|
||||
"actual": actual,
|
||||
"match": True,
|
||||
"marker_source": 1,
|
||||
"marker_restore": 0,
|
||||
}
|
||||
save("recovery.json", recovery)
|
||||
# Sanitized, compact evidence; raw archive stays ignored.
|
||||
evidence = ROOT / "evidence" / "track2" / args.run_id
|
||||
evidence.mkdir(parents=True, exist_ok=False)
|
||||
for p in output.glob("*.json"):
|
||||
(evidence / p.name).write_bytes(p.read_bytes())
|
||||
(evidence / "queries.sql").write_bytes((output / "queries.sql").read_bytes())
|
||||
for name in ["commands.jsonl", "protocol-before-run.md"]:
|
||||
(evidence / name).write_bytes((output / name).read_bytes())
|
||||
print(f"PASS: {project}; evidence: {evidence}; archive: {output}", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,24 @@
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ('11111111-1111-4111-8111-111111111111', 'track2_benchmark',
|
||||
'Track 2 benchmark', decode('00', 'hex'), '2026-01-01 00:00:00+00');
|
||||
|
||||
INSERT INTO chats (id, title, created_at) VALUES
|
||||
('22222222-2222-4222-8222-222222222221', 'Track 2 large', '2026-01-01 00:00:00+00'),
|
||||
('22222222-2222-4222-8222-222222222222', 'Track 2 medium', '2026-01-01 00:00:00+00'),
|
||||
('22222222-2222-4222-8222-222222222223', 'Track 2 small', '2026-01-01 00:00:00+00');
|
||||
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT id, '11111111-1111-4111-8111-111111111111'::uuid FROM chats;
|
||||
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT md5('track2:' || sizes.chat_id::text || ':' || n::text)::uuid,
|
||||
sizes.chat_id,
|
||||
'11111111-1111-4111-8111-111111111111'::uuid,
|
||||
'Track 2 message ' || n::text || ' in ' || sizes.label,
|
||||
'2026-01-01 00:00:00+00'::timestamptz + n * interval '1 microsecond'
|
||||
FROM (VALUES
|
||||
('22222222-2222-4222-8222-222222222221'::uuid, 'large', 100000),
|
||||
('22222222-2222-4222-8222-222222222222'::uuid, 'medium', 15000),
|
||||
('22222222-2222-4222-8222-222222222223'::uuid, 'small', 5000)
|
||||
) AS sizes(chat_id, label, message_count)
|
||||
CROSS JOIN LATERAL generate_series(1, sizes.message_count) AS n;
|
||||
@@ -13,6 +13,18 @@ function errorText(error: unknown): string {
|
||||
: error.message;
|
||||
}
|
||||
return error instanceof Error ? error.message : "Неизвестная ошибка";
|
||||
}
|
||||
|
||||
function authErrorText(error: unknown): string {
|
||||
if (!(error instanceof ApiError)) return errorText(error);
|
||||
const message = error.status === 409
|
||||
? "Имя пользователя уже занято. Выберите другое или войдите."
|
||||
: error.status === 401
|
||||
? "Неверное имя пользователя или пароль."
|
||||
: error.status === 503
|
||||
? "Сервер временно недоступен. Попробуйте ещё раз позже."
|
||||
: error.message;
|
||||
return error.requestId ? `${message} · запрос ${error.requestId}` : message;
|
||||
}
|
||||
|
||||
function dateText(value: string): string {
|
||||
@@ -32,17 +44,36 @@ function AuthForm({ onSuccess }: { onSuccess: (session: Session) => void }) {
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError("");
|
||||
const name = username.trim();
|
||||
if (!/^[a-z0-9_]{3,32}$/.test(name)) {
|
||||
setError("Имя пользователя: 3–32 символа, только строчные латинские буквы, цифры и _.");
|
||||
return;
|
||||
}
|
||||
const passwordLength = Array.from(password).length;
|
||||
if (passwordLength < 12 || passwordLength > 128 || (mode === "register" && !password.trim())) {
|
||||
setError("Пароль должен содержать от 12 до 128 символов.");
|
||||
return;
|
||||
}
|
||||
if (mode === "register" && (!displayName.trim() || Array.from(displayName.trim()).length > 100)) {
|
||||
setError("Отображаемое имя должно содержать от 1 до 100 символов.");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError("");
|
||||
let created = false;
|
||||
try {
|
||||
if (mode === "register") {
|
||||
await api.register(username, displayName, password);
|
||||
await api.register(name, displayName.trim(), password);
|
||||
created = true;
|
||||
}
|
||||
const session = await api.login(username, password);
|
||||
const session = await api.login(name, password);
|
||||
setPassword("");
|
||||
onSuccess(session);
|
||||
} catch (cause) {
|
||||
setError(errorText(cause));
|
||||
setError(created
|
||||
? `Аккаунт создан, но войти не удалось. Повторите вход: ${authErrorText(cause)}`
|
||||
: authErrorText(cause));
|
||||
if (created) setMode("login");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -57,7 +88,7 @@ function AuthForm({ onSuccess }: { onSuccess: (session: Session) => void }) {
|
||||
<button type="button" aria-pressed={mode === "login"} className={mode === "login" ? "active" : ""} onClick={() => { setMode("login"); setError(""); }}>Вход</button>
|
||||
<button type="button" aria-pressed={mode === "register"} className={mode === "register" ? "active" : ""} onClick={() => { setMode("register"); setError(""); }}>Регистрация</button>
|
||||
</div>
|
||||
<form onSubmit={submit} className="stack">
|
||||
<form onSubmit={submit} className="stack" noValidate>
|
||||
<label>
|
||||
Имя пользователя
|
||||
<input value={username} onChange={(event) => setUsername(event.target.value)} required minLength={3} maxLength={32} pattern="[a-z0-9_]+" autoComplete="username" placeholder="ivan_01" />
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
const apiProxy = {
|
||||
target: process.env.API_PROXY_TARGET || "http://localhost:8080",
|
||||
changeOrigin: true,
|
||||
};
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
@@ -9,10 +14,8 @@ export default defineConfig({
|
||||
strictPort: true,
|
||||
watch: { usePolling: true },
|
||||
proxy: {
|
||||
"/api/v1": {
|
||||
target: process.env.API_PROXY_TARGET || "http://localhost:8080",
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/api/v1": apiProxy,
|
||||
"/health": apiProxy,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user