feat: add HAproxy and 2 api instances

This commit is contained in:
TAskMAster339
2026-10-10 13:20:58 +03:00
parent a856733fe9
commit 771951cad7
23 changed files with 742 additions and 213 deletions
+1
View File
@@ -0,0 +1 @@
*.sh text eol=lf
+2 -1
View File
@@ -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 .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: 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-down: stop application; keep database and session volumes"
@echo "app-logs / app-status: inspect application" @echo "app-logs / app-status: inspect application"
@echo "test-backend: Go race tests against PostgreSQL and Redis" @echo "test-backend: Go race tests against PostgreSQL and Redis"
@@ -17,6 +17,7 @@ help:
app-up: app-up:
$(PYTHON) scripts/init_env.py $(PYTHON) scripts/init_env.py
chmod +x scripts/restart.sh scripts/stop-one.sh
$(COMPOSE) up -d --build --wait $(COMPOSE) up -d --build --wait
app-down: app-down:
+30 -4
View File
@@ -24,17 +24,28 @@ services:
interval: 3s interval: 3s
timeout: 3s timeout: 3s
retries: 20 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: api:
build: ./src build: ./src
deploy:
replicas: 2
stop_grace_period: 15s
environment: environment:
APP_HOST: 0.0.0.0 APP_HOST: 0.0.0.0
APP_PORT: 8080 APP_PORT: 8080
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
REDIS_ADDR: redis:6379 REDIS_ADDR: redis:6379
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
ports:
- "127.0.0.1:8080:8080"
depends_on: depends_on:
migrate:
condition: service_completed_successfully
db: db:
condition: service_healthy condition: service_healthy
redis: redis:
@@ -44,6 +55,21 @@ services:
interval: 5s interval: 5s
timeout: 3s timeout: 3s
retries: 20 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: backend-tests:
profiles: ["test"] profiles: ["test"]
build: build:
@@ -62,14 +88,14 @@ services:
build: build:
context: ./src/frontend context: ./src/frontend
environment: environment:
API_PROXY_TARGET: http://api:8080 API_PROXY_TARGET: http://haproxy:8080
ports: ports:
- "127.0.0.1:5173:5173" - "127.0.0.1:5173:5173"
volumes: volumes:
- ./src/frontend:/app - ./src/frontend:/app
- /app/node_modules - /app/node_modules
depends_on: depends_on:
api: haproxy:
condition: service_healthy condition: service_healthy
healthcheck: healthcheck:
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:5173/').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"] test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:5173/').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]
+46
View File
@@ -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
+7 -3
View File
@@ -68,13 +68,15 @@ def main():
token, token,
) )
path = "/api/v1/chats/" + chat["id"] + "/messages" path = "/api/v1/chats/" + chat["id"] + "/messages"
key = secrets.token_hex(16)
body = {"text": "Перенос из лабораторной 2"}
message = call( message = call(
"POST", "POST",
path, path,
201, 201,
{"text": "Перенос из лабораторной 2"}, body,
token, token,
{"Idempotency-Key": secrets.token_hex(16)}, {"Idempotency-Key": key},
) )
assert call("GET", path, token=bob_token)["items"] == [message] assert call("GET", path, token=bob_token)["items"] == [message]
call("GET", "/api/v1/users/me", 401) call("GET", "/api/v1/users/me", 401)
@@ -84,11 +86,13 @@ def main():
subprocess.run(["make", "app-up"], cwd=root, check=True) subprocess.run(["make", "app-up"], cwd=root, check=True)
assert call("GET", "/api/v1/users/me", token=token) == alice assert call("GET", "/api/v1/users/me", token=token) == alice
assert call("GET", path, token=bob_token)["items"] == [message] 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("DELETE", "/api/v1/auth/sessions/current", 204, token=token)
call("GET", "/api/v1/users/me", 401, token=token) call("GET", "/api/v1/users/me", 401, token=token)
print( print(
"PASS: transferred API, shared sessions, chat, message, logout" "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 "")
) )
+102
View File
@@ -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)
+65
View File
@@ -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)
+16
View File
@@ -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
+2 -2
View File
@@ -49,7 +49,7 @@ func writeServiceError(w http.ResponseWriter, err error, requestID string) {
case errors.As(err, &invalid): case errors.As(err, &invalid):
writeError(w, 400, "invalid_request", invalid.Message, requestID) writeError(w, 400, "invalid_request", invalid.Message, requestID)
case errors.Is(err, services.ErrConflict): 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): case errors.Is(err, services.ErrUnknownUser):
writeError(w, 401, "unauthorized", "unknown user", requestID) writeError(w, 401, "unauthorized", "unknown user", requestID)
case errors.Is(err, services.ErrChatNotFound): 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/users/me", authRequired(sessions, currentUserHandler(users)))
mux.Handle("/api/v1/chats", authRequired(sessions, chatCollectionHandler(chats))) mux.Handle("/api/v1/chats", authRequired(sessions, chatCollectionHandler(chats)))
mux.Handle("/api/v1/chats/", authRequired(sessions, chatSubresourceHandler(chats, messages))) mux.Handle("/api/v1/chats/", authRequired(sessions, chatSubresourceHandler(chats, messages)))
return mux return withInstance(mux)
} }
+34
View File
@@ -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)
})
}
+16 -2
View File
@@ -1,6 +1,7 @@
package handlers package handlers
import ( import (
"encoding/json"
"net/http" "net/http"
"strings" "strings"
@@ -9,7 +10,8 @@ import (
) )
type createMessageRequest struct { type createMessageRequest struct {
Text string `json:"text"` Text string `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
} }
func messageChatID(path string) (string, bool) { 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) writeError(w, 400, "invalid_request", "invalid JSON body", requestID)
return 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 { if err != nil {
writeServiceError(w, err, requestID) writeServiceError(w, err, requestID)
return return
+1
View File
@@ -116,6 +116,7 @@ func main() {
case <-shutdownContext.Done(): case <-shutdownContext.Done():
log.Printf("shutdown signal received") log.Printf("shutdown signal received")
handlers.BeginShutdown()
shutdownDeadline, cancel := context.WithTimeout( shutdownDeadline, cancel := context.WithTimeout(
context.Background(), context.Background(),
-4
View File
@@ -52,10 +52,6 @@ func OpenDatabase(ctx context.Context) (*pgxpool.Pool, error) {
db.Close() db.Close()
return nil, err return nil, err
} }
if err = RunMigrations(url, "up"); err != nil {
db.Close()
return nil, err
}
return db, nil return db, nil
} }
+64
View File
@@ -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)
}
@@ -0,0 +1 @@
DROP TABLE message_idempotency;
@@ -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)
);
+30
View File
@@ -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
}
+1
View File
@@ -87,6 +87,7 @@ func TestConcurrentMessageCreation(t *testing.T) {
request.Header.Set("Content-Type", "application/json") request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", tokens[index]) request.Header.Set("Authorization", tokens[index])
request.Header.Set("Idempotency-Key", fmt.Sprintf("client-%d-message-%d", index, messageIndex))
response, err := client.Do(request) response, err := client.Do(request)
if err != nil { if err != nil {
+100
View File
@@ -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")
}
}
+6
View File
@@ -7,7 +7,10 @@ import (
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
"strings"
"testing" "testing"
"github.com/google/uuid"
) )
func TestMessengerWorkflow(t *testing.T) { func TestMessengerWorkflow(t *testing.T) {
@@ -19,6 +22,9 @@ func TestMessengerWorkflow(t *testing.T) {
if body != "" { if body != "" {
request.Header.Set("Content-Type", "application/json") request.Header.Set("Content-Type", "application/json")
} }
if method == http.MethodPost && strings.HasSuffix(path, "/messages") {
request.Header.Set("Idempotency-Key", uuid.NewString())
}
if auth != "" { if auth != "" {
request.Header.Set("Authorization", auth) request.Header.Set("Authorization", auth)
} }
+7
View File
@@ -78,6 +78,13 @@ func newTestFixture(t *testing.T) *testFixture {
t.Fatal(err) t.Fatal(err)
} }
redisClient := repositories.NewRedisClient(redisAddress) 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() }) t.Cleanup(func() { _ = redisClient.Close() })
if err := redisClient.Ping(ctx).Err(); err != nil { if err := redisClient.Ping(ctx).Err(); err != nil {
t.Fatal(err) t.Fatal(err)
+8 -2
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState, type FormEvent } from "react"; import { useCallback, useEffect, useRef, useState, type FormEvent } from "react";
import { api, ApiError, type Chat, type Session, type User } from "./api"; import { api, ApiError, type Chat, type Session, type User } from "./api";
import Pagination from "./Pagination"; import Pagination from "./Pagination";
@@ -119,6 +119,7 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog
const [drafts, setDrafts] = useState<Record<string, string>>({}); const [drafts, setDrafts] = useState<Record<string, string>>({});
const [creating, setCreating] = useState(false); const [creating, setCreating] = useState(false);
const [sending, setSending] = useState(false); const [sending, setSending] = useState(false);
const pendingMessages = useRef<Record<string, { text: string; key: string }>>({});
const [error, setError] = useState(""); const [error, setError] = useState("");
const [notice, setNotice] = useState(""); const [notice, setNotice] = useState("");
const reportError = useCallback((cause: unknown) => { const reportError = useCallback((cause: unknown) => {
@@ -147,9 +148,14 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog
event.preventDefault(); event.preventDefault();
const text = (drafts[chatId] || "").trim(); const text = (drafts[chatId] || "").trim();
if (!text) return; if (!text) return;
const previous = pendingMessages.current[chatId];
const pending = previous?.text === text ? previous : { text, key: crypto.randomUUID() };
// A manual retry after an uncertain response keeps the original key/body.
pendingMessages.current[chatId] = pending;
setSending(true); setError(""); setSending(true); setError("");
try { try {
await api.sendMessage(token, chatId, text); await api.sendMessage(token, chatId, text, pending.key);
delete pendingMessages.current[chatId];
setDrafts((previous) => ({ ...previous, [chatId]: "" })); setDrafts((previous) => ({ ...previous, [chatId]: "" }));
messages.reload(); setNotice("Сообщение отправлено"); messages.reload(); setNotice("Сообщение отправлено");
} catch (cause) { reportError(cause); } } catch (cause) { reportError(cause); }
+2 -2
View File
@@ -118,10 +118,10 @@ export const api = {
headers: bearer(token), headers: bearer(token),
}); });
}, },
sendMessage: (token: string, chatId: string, text: string) => sendMessage: (token: string, chatId: string, text: string, idempotencyKey: string) =>
request<Message>(`/api/v1/chats/${encodeURIComponent(chatId)}/messages`, { request<Message>(`/api/v1/chats/${encodeURIComponent(chatId)}/messages`, {
method: "POST", method: "POST",
headers: { ...bearer(token), "Content-Type": "application/json" }, headers: { ...bearer(token), "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
body: JSON.stringify({ text }), body: JSON.stringify({ text }),
}), }),
}; };