diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfdb8b7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf diff --git a/Makefile b/Makefile index c17c301..230d502 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,7 @@ TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) .PHONY: help app-up app-down app-logs app-status test-backend test-baseline test-baseline-persistence check validate test load test-persistence test-failover help: - @echo "app-up: prepare local environment, build and start API, PostgreSQL, Redis and frontend" + @echo "app-up: prepare local environment, migrate, build and start HAProxy, two API replicas, PostgreSQL, Redis and frontend" @echo "app-down: stop application; keep database and session volumes" @echo "app-logs / app-status: inspect application" @echo "test-backend: Go race tests against PostgreSQL and Redis" @@ -17,6 +17,7 @@ help: app-up: $(PYTHON) scripts/init_env.py + chmod +x scripts/restart.sh scripts/stop-one.sh $(COMPOSE) up -d --build --wait app-down: diff --git a/compose.yml b/compose.yml index 76f5e46..a87c059 100644 --- a/compose.yml +++ b/compose.yml @@ -24,17 +24,28 @@ services: interval: 3s timeout: 3s retries: 20 + migrate: + build: ./src + environment: + DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable + command: ["./messenger", "migrate", "up"] + depends_on: + db: + condition: service_healthy api: build: ./src + deploy: + replicas: 2 + stop_grace_period: 15s environment: APP_HOST: 0.0.0.0 APP_PORT: 8080 SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} REDIS_ADDR: redis:6379 DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable - ports: - - "127.0.0.1:8080:8080" depends_on: + migrate: + condition: service_completed_successfully db: condition: service_healthy redis: @@ -44,6 +55,21 @@ services: interval: 5s timeout: 3s retries: 20 + haproxy: + image: haproxy:3.2.25-alpine + ports: + - "127.0.0.1:8080:8080" + - "127.0.0.1:8404:8404" + volumes: + - ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + depends_on: + api: + condition: service_healthy + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"] + interval: 2s + timeout: 3s + retries: 20 backend-tests: profiles: ["test"] build: @@ -62,14 +88,14 @@ services: build: context: ./src/frontend environment: - API_PROXY_TARGET: http://api:8080 + API_PROXY_TARGET: http://haproxy:8080 ports: - "127.0.0.1:5173:5173" volumes: - ./src/frontend:/app - /app/node_modules depends_on: - api: + haproxy: condition: service_healthy healthcheck: test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:5173/').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"] diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg new file mode 100644 index 0000000..8bb7282 --- /dev/null +++ b/infra/haproxy.cfg @@ -0,0 +1,46 @@ +global + log stdout format raw local0 + maxconn 1024 + +defaults + log global + mode http + option httplog + timeout connect 1s + timeout client 15s + timeout server 12s + timeout check 1s + # Let the client decide which failed POST is safe to repeat. + retries 0 + +# Docker returns the current addresses of all containers of the api service. +resolvers docker + nameserver docker_dns 127.0.0.11:53 + accepted_payload_size 8192 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 1s + hold obsolete 1s + hold nx 1s + hold timeout 1s + hold refused 1s + hold other 1s + +frontend api_entry + bind :8080 + default_backend api_replicas + +backend api_replicas + balance roundrobin + option httpchk GET /health/ready + http-check expect status 200 + # Separate slots receive distinct Docker DNS addresses. No sticky sessions. + server-template api 2 api:8080 check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr libc,none + +# Local teaching aid: backend addresses, UP/DOWN state and request counters. +listen statistics + bind :8404 + stats enable + stats uri /stats + stats refresh 2s diff --git a/scripts/check_baseline.py b/scripts/check_baseline.py index 1448b66..49055ad 100644 --- a/scripts/check_baseline.py +++ b/scripts/check_baseline.py @@ -68,13 +68,15 @@ def main(): token, ) path = "/api/v1/chats/" + chat["id"] + "/messages" + key = secrets.token_hex(16) + body = {"text": "Перенос из лабораторной 2"} message = call( "POST", path, 201, - {"text": "Перенос из лабораторной 2"}, + body, token, - {"Idempotency-Key": secrets.token_hex(16)}, + {"Idempotency-Key": key}, ) assert call("GET", path, token=bob_token)["items"] == [message] call("GET", "/api/v1/users/me", 401) @@ -84,11 +86,13 @@ def main(): subprocess.run(["make", "app-up"], cwd=root, check=True) assert call("GET", "/api/v1/users/me", token=token) == alice assert call("GET", path, token=bob_token)["items"] == [message] + assert call("POST", path, 201, body, token, {"Idempotency-Key": key}) == message + assert call("GET", path, token=bob_token)["items"] == [message] call("DELETE", "/api/v1/auth/sessions/current", 204, token=token) call("GET", "/api/v1/users/me", 401, token=token) print( "PASS: transferred API, shared sessions, chat, message, logout" - + (", persistence across app-down/app-up" if args.restart else "") + + (", persistence and idempotent replay across app-down/app-up" if args.restart else "") ) diff --git a/scripts/check_failover.py b/scripts/check_failover.py new file mode 100644 index 0000000..dcacc8f --- /dev/null +++ b/scripts/check_failover.py @@ -0,0 +1,102 @@ +import json +import os +import subprocess +import sys +import time +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, arguments, check, run +from resilience import history + +COMPOSE = ["docker", "compose", "--project-name", "highload-lab3", "--env-file", ".env", "-f", "compose.yml"] + + +def inspect(container): + # Deliberately inspect only public identity/state, not credentials or env. + raw = subprocess.check_output(["docker", "inspect", "--format", + '{{json .Config.Hostname}} {{json .State.Status}}', container], text=True) + hostname, state = raw.strip().split() + return json.loads(hostname), json.loads(state) + + +def restore(): + subprocess.run(COMPOSE + ["up", "-d", "--wait", "--no-deps", "api"], cwd=ROOT, check=True) + + +def main(): + args = arguments(__doc__) + c = Client(args.base_url, args.ca_file, timeout=2) + containers = subprocess.check_output(COMPOSE + ["ps", "-q", "api"], cwd=ROOT, text=True).split() + check(len(containers) >= 2, "need at least two running API containers") + targets = [(container, inspect(container)[0]) for container in containers] + alice, bob, _, chat = c.bootstrap() + records = [] + for container, target in targets: + # Read through the LB using one existing session until all replicas rejoin. + seen = set() + deadline = time.monotonic() + 10 + while len(seen) < len(targets) and time.monotonic() < deadline: + seen.add(c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"]["X-Instance-Id"]) + time.sleep(0.05) + check(target in seen and len(seen) >= 2, "restored replica is not serving through HAProxy") + confirmed_key = uuid.uuid4().hex + confirmed_text = "Before failure " + confirmed_key + original = c.message(alice, chat, confirmed_text, key=confirmed_key)["json"] + env = dict(os.environ, TARGET_INSTANCE_ID=target) + started = time.monotonic() + proc = subprocess.Popen([str(ROOT / "scripts" / "stop-one.sh")], cwd=ROOT, env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + successes, last_instances = [], [] + write_errors = read_errors = reads = 0 + first_write = first_read = None + key = uuid.uuid4().hex + try: + while time.monotonic() - started < 15: + check(proc.poll() in (None, 0), "stop-one hook failed") + try: + result = c.message(alice, chat, "During failure " + key, key=key) + successes.append(result["json"]) + if proc.poll() == 0: + last_instances.append(result["headers"]["X-Instance-Id"]) + if first_write is None: + first_write = time.monotonic() - started + key = uuid.uuid4().hex + except Failure: + write_errors += 1 # Retry the SAME key and text on the next iteration. + try: + c.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage") + reads += 1 + if proc.poll() == 0 and first_read is None: + first_read = time.monotonic() - started + except Failure: + read_errors += 1 + time.sleep(0.1) + check(proc.poll() == 0, "stop-one hook did not finish") + check(inspect(container)[1] == "exited", "target container did not stay stopped") + check(first_write is not None and first_write <= 10, "writes did not recover within 10 seconds") + check(first_read is not None and first_read <= 10, "reads did not recover within 10 seconds") + check(len(last_instances) >= 5 and target not in last_instances[-5:], "stopped replica still serves responses") + check(c.message(alice, chat, confirmed_text, key=confirmed_key)["json"] == original, + "replay after switching replicas changed a confirmed message") + messages = history(c, bob, chat) + check(all(message in messages for message in [original] + successes), "confirmed message lost") + texts = [message["text"] for message in messages] + check(len(texts) == len(set(texts)), "uncertain retry created a duplicate") + record = {"stopped_instance": target, "container_state": "exited", "successful_writes": len(successes), + "successful_reads": reads, "write_errors": write_errors, "read_errors": read_errors, + "first_write_seconds": round(first_write, 3), "first_read_seconds": round(first_read, 3)} + records.append(record) + print(json.dumps(record), flush=True) + finally: + if proc.poll() is None: + proc.terminate() + proc.wait(timeout=5) + restore() + print("PASS: each API replica stopped in turn; reads, writes, sessions and confirmed messages preserved") + + +if __name__ == "__main__": + run(main) diff --git a/scripts/check_idempotency.py b/scripts/check_idempotency.py new file mode 100644 index 0000000..a6614dc --- /dev/null +++ b/scripts/check_idempotency.py @@ -0,0 +1,65 @@ +import json +import sys +import uuid +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from threading import Barrier + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from client import Client, arguments, check, run + + +def main(): + args = arguments(__doc__) + c = Client(args.base_url, args.ca_file) + alice, bob, eve, chat = c.bootstrap() + path = "/api/v1/chats/" + chat["id"] + "/messages" + observed = { + c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"]["X-Instance-Id"] + for _ in range(40) + } + check(len(observed) >= 2, "same session did not reach two API replicas") + + key = uuid.uuid4().hex + text = "Один ключ через разные реплики 👋" + concurrency = 24 + start = Barrier(concurrency) + + def send(_): + client = Client(args.base_url, args.ca_file) + start.wait(timeout=15) + return client.message(alice, chat, text, key=key) + + with ThreadPoolExecutor(max_workers=concurrency) as pool: + replies = list(pool.map(send, range(concurrency))) + original = replies[0]["json"] + instances = {reply["headers"]["X-Instance-Id"] for reply in replies} + check(len(instances) >= 2, "concurrent POST did not reach different API replicas") + check(all(reply["json"] == original for reply in replies), "concurrent replay changed the response") + history = c.call("GET", path, actor=bob, schema="MessagePage")["json"]["items"] + check(history == [original], "concurrent POST created a duplicate") + check(c.message(alice, chat, text, key=key, attachments=[])["json"] == original, "empty attachment_ids changed replay") + reordered = c.call("POST", path, 201, actor=alice, + raw=json.dumps({"attachment_ids": [], "text": text}, ensure_ascii=False).encode(), + headers={"Content-Type": "application/json", "Idempotency-Key": key}, schema="Message")["json"] + check(reordered == original, "JSON key order changed replay") + c.call("POST", path, 409, actor=alice, body={"text": "другое тело"}, headers={"Idempotency-Key": key}) + c.call("POST", path, 400, actor=alice, body={"text": text}) + for invalid in ("bad key", "x" * 129, "invalid/key", ""): + c.call("POST", path, 400, actor=alice, body={"text": text}, headers={"Idempotency-Key": invalid}) + c.call("POST", path, 400, actor=alice, body={"text": text, "extra": 1}, headers={"Idempotency-Key": key}) + c.call("POST", path, 404, actor=eve, body={"text": text}, headers={"Idempotency-Key": key}) + other_sender = c.message(bob, chat, text, key=key)["json"] + check(other_sender["id"] != original["id"], "key scope does not include sender") + other_chat = c.call("POST", "/api/v1/chats", 201, actor=alice, + body={"title": "Other scope", "member_ids": [alice["id"]]}, schema="Chat")["json"] + check(c.message(alice, other_chat, text, key=key)["json"]["id"] != original["id"], "key scope does not include chat") + c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice) + c.call("POST", path, 401, actor=alice, body={"text": text}, headers={"Idempotency-Key": key}) + print(json.dumps({"concurrent_requests": concurrency, "observed_instances": sorted(instances), + "messages_after_concurrent_repeat": len(history)}, ensure_ascii=False)) + print("PASS: shared session, concurrent replay across replicas, key/body validation, independent scopes, reauthentication on replay") + + +if __name__ == "__main__": + run(main) diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 0000000..795a807 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." + +: "${TARGET_INSTANCE_ID:?Set TARGET_INSTANCE_ID to the X-Instance-Id of an API replica}" +for container in $(docker compose --project-name highload-lab3 --env-file .env -f compose.yml ps -q api); do + hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container") + if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then + # Only containers from this Compose project's api service are eligible. + docker stop --timeout 8 "$container" >/dev/null + printf 'Stopped API instance %s\n' "$hostname" + exit 0 + fi +done +printf 'No running API replica matches TARGET_INSTANCE_ID\n' >&2 +exit 1 diff --git a/src/backend/handlers/http.go b/src/backend/handlers/http.go index 6efd7ef..bbfcb71 100644 --- a/src/backend/handlers/http.go +++ b/src/backend/handlers/http.go @@ -49,7 +49,7 @@ func writeServiceError(w http.ResponseWriter, err error, requestID string) { case errors.As(err, &invalid): writeError(w, 400, "invalid_request", invalid.Message, requestID) case errors.Is(err, services.ErrConflict): - writeError(w, 409, "conflict", "username is already taken", requestID) + writeError(w, 409, "conflict", "request conflicts with an existing resource", requestID) case errors.Is(err, services.ErrUnknownUser): writeError(w, 401, "unauthorized", "unknown user", requestID) case errors.Is(err, services.ErrChatNotFound): @@ -139,5 +139,5 @@ func NewRouter(health *services.HealthService, users *services.UserService, sess mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(users))) mux.Handle("/api/v1/chats", authRequired(sessions, chatCollectionHandler(chats))) mux.Handle("/api/v1/chats/", authRequired(sessions, chatSubresourceHandler(chats, messages))) - return mux + return withInstance(mux) } diff --git a/src/backend/handlers/instance.go b/src/backend/handlers/instance.go new file mode 100644 index 0000000..5421f18 --- /dev/null +++ b/src/backend/handlers/instance.go @@ -0,0 +1,34 @@ +package handlers + +import ( + "net/http" + "os" + "sync/atomic" + + "github.com/google/uuid" +) + +// Docker's hostname lets the operator map an API response to its container. +var instanceID = func() string { + id, err := os.Hostname() + if err != nil || id == "" { + return uuid.NewString() + } + return id +}() + +var draining atomic.Bool + +func BeginShutdown() { draining.Store(true) } + +func withInstance(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Instance-Id", instanceID) + w.Header().Set("X-Request-Id", newRequestID()) + if draining.Load() && r.URL.Path != "/health/live" { + writeError(w, 503, "unavailable", "instance is shutting down", w.Header().Get("X-Request-Id")) + return + } + next.ServeHTTP(w, r) + }) +} diff --git a/src/backend/handlers/message_http.go b/src/backend/handlers/message_http.go index d42ca6a..a2f6aed 100644 --- a/src/backend/handlers/message_http.go +++ b/src/backend/handlers/message_http.go @@ -1,6 +1,7 @@ package handlers import ( + "encoding/json" "net/http" "strings" @@ -9,7 +10,8 @@ import ( ) type createMessageRequest struct { - Text string `json:"text"` + Text string `json:"text"` + AttachmentIDs json.RawMessage `json:"attachment_ids"` } func messageChatID(path string) (string, bool) { @@ -60,7 +62,19 @@ func createMessageHandler(chats *services.ChatService, messages *services.Messag writeError(w, 400, "invalid_request", "invalid JSON body", requestID) return } - message, err := messages.Create(r.Context(), userID, chat, request.Text) + if len(request.AttachmentIDs) > 0 { + var ids []string + if err := json.Unmarshal(request.AttachmentIDs, &ids); err != nil || ids == nil || len(ids) != 0 { + writeError(w, 400, "invalid_request", "attachments are not supported in lab3; use an empty array or omit attachment_ids", requestID) + return + } + } + keys := r.Header.Values("Idempotency-Key") + if len(keys) != 1 { + writeError(w, 400, "invalid_request", "exactly one Idempotency-Key is required", requestID) + return + } + message, err := messages.CreateIdempotent(r.Context(), userID, chat, request.Text, keys[0]) if err != nil { writeServiceError(w, err, requestID) return diff --git a/src/backend/main.go b/src/backend/main.go index c1246ae..1c002f3 100644 --- a/src/backend/main.go +++ b/src/backend/main.go @@ -116,6 +116,7 @@ func main() { case <-shutdownContext.Done(): log.Printf("shutdown signal received") + handlers.BeginShutdown() shutdownDeadline, cancel := context.WithTimeout( context.Background(), diff --git a/src/backend/repositories/database.go b/src/backend/repositories/database.go index 0ac06f8..6fa290e 100644 --- a/src/backend/repositories/database.go +++ b/src/backend/repositories/database.go @@ -52,10 +52,6 @@ func OpenDatabase(ctx context.Context) (*pgxpool.Pool, error) { db.Close() return nil, err } - if err = RunMigrations(url, "up"); err != nil { - db.Close() - return nil, err - } return db, nil } diff --git a/src/backend/repositories/idempotency.go b/src/backend/repositories/idempotency.go new file mode 100644 index 0000000..a1b8093 --- /dev/null +++ b/src/backend/repositories/idempotency.go @@ -0,0 +1,64 @@ +package repositories + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +var ErrIdempotencyConflict = errors.New("idempotency key belongs to a different message") + +// CreateIdempotent commits the message and its replay record together. +func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, text, key string) (Message, error) { + ctx, cancel := boundedQuery(ctx) + defer cancel() + tx, err := s.db.Begin(ctx) + if err != nil { + return Message{}, err + } + defer tx.Rollback(context.Background()) + + // The transaction-scoped lock is shared by all API replicas. Hash collisions + // only serialize unrelated requests; the full scope is checked by the query. + scope := senderID + ":POST:/api/v1/chats/" + chatID + "/messages:" + key + if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", scope); err != nil { + return Message{}, err + } + var message Message + err = tx.QueryRow(ctx, ` + SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at + FROM message_idempotency i JOIN messages m ON m.id = i.message_id + WHERE i.sender_id=$1 AND i.chat_id=$2 AND i.key=$3 + AND i.expires_at > clock_timestamp()`, senderID, chatID, key). + Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt) + if err == nil { + message.CreatedAt = message.CreatedAt.UTC() + if message.Text != text { + return Message{}, ErrIdempotencyConflict + } + return message, tx.Commit(ctx) + } + if !errors.Is(err, pgx.ErrNoRows) { + return Message{}, err + } + + // Expiry permits reuse after 24 hours; it never deletes the original message. + if _, err = tx.Exec(ctx, "DELETE FROM message_idempotency WHERE sender_id=$1 AND chat_id=$2 AND key=$3", senderID, chatID, key); err != nil { + return Message{}, err + } + message = Message{ + ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text, + CreatedAt: time.Now().UTC().Truncate(time.Microsecond), + } + if _, err = tx.Exec(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", message.ID, chatID, senderID, text, message.CreatedAt); err != nil { + return Message{}, err + } + if _, err = tx.Exec(ctx, `INSERT INTO message_idempotency(sender_id,chat_id,key,message_id,expires_at) + VALUES($1,$2,$3,$4,clock_timestamp() + interval '24 hours')`, senderID, chatID, key, message.ID); err != nil { + return Message{}, err + } + return message, tx.Commit(ctx) +} diff --git a/src/backend/repositories/migrations/000003_message_idempotency.down.sql b/src/backend/repositories/migrations/000003_message_idempotency.down.sql new file mode 100644 index 0000000..64acde8 --- /dev/null +++ b/src/backend/repositories/migrations/000003_message_idempotency.down.sql @@ -0,0 +1 @@ +DROP TABLE message_idempotency; diff --git a/src/backend/repositories/migrations/000003_message_idempotency.up.sql b/src/backend/repositories/migrations/000003_message_idempotency.up.sql new file mode 100644 index 0000000..e99a860 --- /dev/null +++ b/src/backend/repositories/migrations/000003_message_idempotency.up.sql @@ -0,0 +1,8 @@ +CREATE TABLE message_idempotency ( + sender_id uuid NOT NULL REFERENCES users(id), + chat_id uuid NOT NULL REFERENCES chats(id), + key varchar(128) NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'), + message_id uuid NOT NULL REFERENCES messages(id), + expires_at timestamptz NOT NULL, + PRIMARY KEY (sender_id, chat_id, key) +); diff --git a/src/backend/services/idempotency.go b/src/backend/services/idempotency.go new file mode 100644 index 0000000..93d86e8 --- /dev/null +++ b/src/backend/services/idempotency.go @@ -0,0 +1,30 @@ +package services + +import ( + "context" + "errors" + "regexp" + "strings" + "unicode/utf8" + + "messenger/src/backend/repositories" +) + +var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +func (s *MessageService) CreateIdempotent(ctx context.Context, userID string, chat repositories.Chat, text, key string) (repositories.Message, error) { + if !ChatHasMember(chat, userID) { + return repositories.Message{}, ErrChatNotFound + } + if !idempotencyKeyPattern.MatchString(key) { + return repositories.Message{}, InvalidInput{"Idempotency-Key must contain 1-128 ASCII letters, digits or ._:-"} + } + if strings.TrimSpace(text) == "" || utf8.RuneCountInString(text) > 4000 { + return repositories.Message{}, InvalidInput{"text must contain 1-4000 characters and must not be blank"} + } + message, err := s.messages.CreateIdempotent(ctx, chat.ID, userID, text, key) + if errors.Is(err, repositories.ErrIdempotencyConflict) { + return repositories.Message{}, ErrConflict + } + return message, err +} diff --git a/src/backend/tests/concurrency_test.go b/src/backend/tests/concurrency_test.go index b0204e9..d642178 100644 --- a/src/backend/tests/concurrency_test.go +++ b/src/backend/tests/concurrency_test.go @@ -87,6 +87,7 @@ func TestConcurrentMessageCreation(t *testing.T) { request.Header.Set("Content-Type", "application/json") request.Header.Set("Authorization", tokens[index]) + request.Header.Set("Idempotency-Key", fmt.Sprintf("client-%d-message-%d", index, messageIndex)) response, err := client.Do(request) if err != nil { diff --git a/src/backend/tests/idempotency_test.go b/src/backend/tests/idempotency_test.go new file mode 100644 index 0000000..5811ee0 --- /dev/null +++ b/src/backend/tests/idempotency_test.go @@ -0,0 +1,100 @@ +package tests + +import ( + "context" + "errors" + "sync" + "testing" + + "messenger/src/backend/repositories" +) + +func TestIdempotencyConcurrentStoresAndScopes(t *testing.T) { + f := newTestFixture(t) + alice, _ := createTestUser(t, f.users, "alice", "Alice") + bob, _ := createTestUser(t, f.users, "bob", "Bob") + chat := createTestChat(t, f.chats, "Chat", []string{alice.ID, bob.ID}) + otherChat := createTestChat(t, f.chats, "Other", []string{alice.ID}) + stores := []*repositories.MessageStore{f.messages, repositories.NewMessageStore(f.db)} + const concurrency = 24 + start := make(chan struct{}) + results := make(chan repositories.Message, concurrency) + errorsFound := make(chan error, concurrency) + var group sync.WaitGroup + for i := 0; i < concurrency; i++ { + group.Add(1) + go func(i int) { + defer group.Done() + <-start + message, err := stores[i%len(stores)].CreateIdempotent(context.Background(), chat.ID, alice.ID, "hello", "same-key") + results <- message + errorsFound <- err + }(i) + } + close(start) + group.Wait() + close(results) + close(errorsFound) + for err := range errorsFound { + if err != nil { + t.Fatal(err) + } + } + var original repositories.Message + for message := range results { + if original.ID == "" { + original = message + } else if message != original { + t.Fatalf("replay changed the message: %v != %v", message, original) + } + } + if len(listTestMessages(t, f.messages, chat.ID)) != 1 { + t.Fatal("concurrent repeat created duplicate messages") + } + if _, err := f.messages.CreateIdempotent(context.Background(), chat.ID, alice.ID, "different", "same-key"); !errors.Is(err, repositories.ErrIdempotencyConflict) { + t.Fatalf("different body: got %v", err) + } + for _, scope := range [][2]string{{chat.ID, bob.ID}, {otherChat.ID, alice.ID}} { + message, err := f.messages.CreateIdempotent(context.Background(), scope[0], scope[1], "hello", "same-key") + if err != nil || message.ID == original.ID { + t.Fatalf("key leaked across scopes: %v", err) + } + } + if _, err := f.db.Exec(context.Background(), "UPDATE message_idempotency SET expires_at=now()-interval '1 second' WHERE message_id=$1", original.ID); err != nil { + t.Fatal(err) + } + reused, err := f.messages.CreateIdempotent(context.Background(), chat.ID, alice.ID, "after expiry", "same-key") + if err != nil || reused.ID == original.ID { + t.Fatalf("expired key cannot be reused: %v", err) + } +} + +func TestIdempotencyRecordFailureRollsBackMessage(t *testing.T) { + f := newTestFixture(t) + alice, _ := createTestUser(t, f.users, "alice", "Alice") + chat := createTestChat(t, f.chats, "Chat", []string{alice.ID}) + // Force a failure AFTER the message insert to verify transaction atomicity. + _, err := f.db.Exec(context.Background(), ` + CREATE FUNCTION reject_replay() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'synthetic replay failure'; END $$; + CREATE TRIGGER reject_replay BEFORE INSERT ON message_idempotency + FOR EACH ROW EXECUTE FUNCTION reject_replay()`) + if err != nil { + t.Fatal(err) + } + if _, err := f.messages.CreateIdempotent(context.Background(), chat.ID, alice.ID, "hello", "retry-key"); err == nil { + t.Fatal("synthetic failure did not happen") + } + if len(listTestMessages(t, f.messages, chat.ID)) != 0 { + t.Fatal("failed transaction left a message behind") + } + if _, err := f.db.Exec(context.Background(), "DROP TRIGGER reject_replay ON message_idempotency"); err != nil { + t.Fatal(err) + } + if _, err := f.messages.CreateIdempotent(context.Background(), chat.ID, alice.ID, "hello", "retry-key"); err != nil { + t.Fatalf("failure was cached instead of permitting retry: %v", err) + } + if len(listTestMessages(t, f.messages, chat.ID)) != 1 { + t.Fatal("retry did not produce exactly one message") + } +} diff --git a/src/backend/tests/integration_test.go b/src/backend/tests/integration_test.go index 1563102..1fec7a6 100644 --- a/src/backend/tests/integration_test.go +++ b/src/backend/tests/integration_test.go @@ -7,7 +7,10 @@ import ( "net/http" "net/http/httptest" "net/url" + "strings" "testing" + + "github.com/google/uuid" ) func TestMessengerWorkflow(t *testing.T) { @@ -19,6 +22,9 @@ func TestMessengerWorkflow(t *testing.T) { if body != "" { request.Header.Set("Content-Type", "application/json") } + if method == http.MethodPost && strings.HasSuffix(path, "/messages") { + request.Header.Set("Idempotency-Key", uuid.NewString()) + } if auth != "" { request.Header.Set("Authorization", auth) } diff --git a/src/backend/tests/test_fixture_test.go b/src/backend/tests/test_fixture_test.go index a96f71e..ade688a 100644 --- a/src/backend/tests/test_fixture_test.go +++ b/src/backend/tests/test_fixture_test.go @@ -78,6 +78,13 @@ func newTestFixture(t *testing.T) *testFixture { t.Fatal(err) } redisClient := repositories.NewRedisClient(redisAddress) + ddl, err = os.ReadFile("../repositories/migrations/000003_message_idempotency.up.sql") + if err != nil { + t.Fatal(err) + } + if _, err = db.Exec(ctx, string(ddl)); err != nil { + t.Fatal(err) + } t.Cleanup(func() { _ = redisClient.Close() }) if err := redisClient.Ping(ctx).Err(); err != nil { t.Fatal(err) diff --git a/src/frontend/src/App.tsx b/src/frontend/src/App.tsx index 39cae93..cb8d933 100644 --- a/src/frontend/src/App.tsx +++ b/src/frontend/src/App.tsx @@ -1,18 +1,18 @@ -import { useCallback, useEffect, useState, type FormEvent } from "react"; -import { api, ApiError, type Chat, type Session, type User } from "./api"; - -import Pagination from "./Pagination"; -import { useCursorPage } from "./useCursorPage"; - -const tokenKey = "messenger_test_token"; - -function errorText(error: unknown): string { - if (error instanceof ApiError) { - return error.requestId - ? `${error.message} · запрос ${error.requestId}` - : error.message; - } - return error instanceof Error ? error.message : "Неизвестная ошибка"; +import { useCallback, useEffect, useRef, useState, type FormEvent } from "react"; +import { api, ApiError, type Chat, type Session, type User } from "./api"; + +import Pagination from "./Pagination"; +import { useCursorPage } from "./useCursorPage"; + +const tokenKey = "messenger_test_token"; + +function errorText(error: unknown): string { + if (error instanceof ApiError) { + return error.requestId + ? `${error.message} · запрос ${error.requestId}` + : error.message; + } + return error instanceof Error ? error.message : "Неизвестная ошибка"; } function authErrorText(error: unknown): string { @@ -25,25 +25,25 @@ function authErrorText(error: unknown): string { ? "Сервер временно недоступен. Попробуйте ещё раз позже." : error.message; return error.requestId ? `${message} · запрос ${error.requestId}` : message; -} - -function dateText(value: string): string { - return new Date(value).toLocaleString("ru-RU", { - dateStyle: "short", - timeStyle: "short", - }); -} - -function AuthForm({ onSuccess }: { onSuccess: (session: Session) => void }) { - const [mode, setMode] = useState<"login" | "register">("login"); - const [username, setUsername] = useState(""); - const [displayName, setDisplayName] = useState(""); - const [password, setPassword] = useState(""); - const [busy, setBusy] = useState(false); - const [error, setError] = useState(""); - - async function submit(event: FormEvent) { - event.preventDefault(); +} + +function dateText(value: string): string { + return new Date(value).toLocaleString("ru-RU", { + dateStyle: "short", + timeStyle: "short", + }); +} + +function AuthForm({ onSuccess }: { onSuccess: (session: Session) => void }) { + const [mode, setMode] = useState<"login" | "register">("login"); + const [username, setUsername] = useState(""); + const [displayName, setDisplayName] = useState(""); + const [password, setPassword] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + + async function submit(event: FormEvent) { + event.preventDefault(); setError(""); const name = username.trim(); if (!/^[a-z0-9_]{3,32}$/.test(name)) { @@ -59,173 +59,179 @@ function AuthForm({ onSuccess }: { onSuccess: (session: Session) => void }) { setError("Отображаемое имя должно содержать от 1 до 100 символов."); return; } - setBusy(true); + setBusy(true); let created = false; - try { - if (mode === "register") { + try { + if (mode === "register") { await api.register(name, displayName.trim(), password); created = true; - } + } const session = await api.login(name, password); - setPassword(""); - onSuccess(session); - } catch (cause) { + setPassword(""); + onSuccess(session); + } catch (cause) { setError(created ? `Аккаунт создан, но войти не удалось. Повторите вход: ${authErrorText(cause)}` : authErrorText(cause)); if (created) setMode("login"); - } finally { - setBusy(false); - } - } - - return ( -
-
- -

Мессенджер

-
- - -
+ } finally { + setBusy(false); + } + } + + return ( +
+
+ +

Мессенджер

+
+ + +
- - {mode === "register" && ( - - )} - - {error &&

{error}

} - -
-
-
- ); -} - -function Workspace({ token, user, onLogout }: { token: string; user: User; onLogout: (notice?: string) => void }) { - const [selectedChat, setSelectedChat] = useState(null); - const [showCreate, setShowCreate] = useState(false); - const [title, setTitle] = useState(""); - const [members, setMembers] = useState(""); - const [drafts, setDrafts] = useState>({}); - const [creating, setCreating] = useState(false); - const [sending, setSending] = useState(false); - const [error, setError] = useState(""); - const [notice, setNotice] = useState(""); - const reportError = useCallback((cause: unknown) => { - if (cause instanceof ApiError && cause.status === 401) onLogout("Сессия истекла. Войдите снова."); - else setError(errorText(cause)); - }, [onLogout]); - const fetchChats = useCallback((cursor: string | undefined, limit: number) => api.chats(token, cursor, limit), [token]); - const chatId = selectedChat?.id || ""; - const fetchMessages = useCallback((cursor: string | undefined, limit: number) => api.messages(token, chatId, cursor, limit), [token, chatId]); - const chats = useCursorPage(token, fetchChats, reportError); - const messages = useCursorPage(chatId, fetchMessages, reportError); - - async function createChat(event: FormEvent) { - event.preventDefault(); - if (!title.trim()) return; - setCreating(true); setError(""); - try { - const memberIds = Array.from(new Set([user.id, ...members.split(/[\s,;]+/).filter(Boolean)])); - const chat = await api.createChat(token, title.trim(), memberIds); - setSelectedChat(chat); setTitle(""); setMembers(""); setShowCreate(false); chats.refresh(); - } catch (cause) { reportError(cause); } - finally { setCreating(false); } - } - - async function sendMessage(event: FormEvent) { - event.preventDefault(); - const text = (drafts[chatId] || "").trim(); - if (!text) return; - setSending(true); setError(""); - try { - await api.sendMessage(token, chatId, text); - setDrafts((previous) => ({ ...previous, [chatId]: "" })); - messages.reload(); setNotice("Сообщение отправлено"); - } catch (cause) { reportError(cause); } - finally { setSending(false); } - } - - async function logout() { - try { await api.logout(token); onLogout(); } - catch (cause) { reportError(cause); } - } - - async function copyId() { - try { await navigator.clipboard.writeText(user.id); setNotice("ID скопирован"); } - catch { setError("Не удалось скопировать ID. Выделите его вручную."); } - } - - return
-
- Мессенджер -
{user.display_name.slice(0, 1).toUpperCase()}
{user.display_name}@{user.username}
-
- {(error || notice) &&
{error || notice}
} -
-