forked from mtusi2026/mtusi2026lab3
feat: add HAproxy and 2 api instances
This commit is contained in:
@@ -0,0 +1 @@
|
||||
*.sh text eol=lf
|
||||
@@ -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:
|
||||
|
||||
+30
-4
@@ -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))"]
|
||||
|
||||
@@ -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
|
||||
@@ -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 "")
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -116,6 +116,7 @@ func main() {
|
||||
|
||||
case <-shutdownContext.Done():
|
||||
log.Printf("shutdown signal received")
|
||||
handlers.BeginShutdown()
|
||||
|
||||
shutdownDeadline, cancel := context.WithTimeout(
|
||||
context.Background(),
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
+201
-195
@@ -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<HTMLFormElement>) {
|
||||
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<HTMLFormElement>) {
|
||||
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 (
|
||||
<main className="auth-page">
|
||||
<div className="auth-card">
|
||||
<div className="brand-mark" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M5 4h14v12H9l-4 4V4Z"/><path d="M9 8h6M9 12h4"/></svg></div>
|
||||
<h1>Мессенджер</h1>
|
||||
<div className="tabs" aria-label="Режим входа">
|
||||
<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>
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="auth-page">
|
||||
<div className="auth-card">
|
||||
<div className="brand-mark" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M5 4h14v12H9l-4 4V4Z"/><path d="M9 8h6M9 12h4"/></svg></div>
|
||||
<h1>Мессенджер</h1>
|
||||
<div className="tabs" aria-label="Режим входа">
|
||||
<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" 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" />
|
||||
</label>
|
||||
{mode === "register" && (
|
||||
<label>
|
||||
Отображаемое имя
|
||||
<input value={displayName} onChange={(event) => setDisplayName(event.target.value)} required maxLength={100} placeholder="Иван" />
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
Пароль
|
||||
<input type="password" value={password} onChange={(event) => setPassword(event.target.value)} required minLength={12} maxLength={128} autoComplete={mode === "register" ? "new-password" : "current-password"} placeholder="Не менее 12 символов" />
|
||||
</label>
|
||||
{error && <p className="error" role="alert">{error}</p>}
|
||||
<button type="submit" className="primary" disabled={busy}>{busy ? "Подождите…" : mode === "register" ? "Создать аккаунт и войти" : "Войти"}</button>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function Workspace({ token, user, onLogout }: { token: string; user: User; onLogout: (notice?: string) => void }) {
|
||||
const [selectedChat, setSelectedChat] = useState<Chat | null>(null);
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [title, setTitle] = useState("");
|
||||
const [members, setMembers] = useState("");
|
||||
const [drafts, setDrafts] = useState<Record<string, string>>({});
|
||||
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<HTMLFormElement>) {
|
||||
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<HTMLFormElement>) {
|
||||
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 <div className="app-shell">
|
||||
<header className="app-header">
|
||||
<a className="brand" href="/">Мессенджер<span className="brand-dot" /></a>
|
||||
<div className="account"><span className="avatar">{user.display_name.slice(0, 1).toUpperCase()}</span><div><strong>{user.display_name}</strong><small>@{user.username}</small></div><button className="quiet" onClick={() => void logout()}>Выйти</button></div>
|
||||
</header>
|
||||
{(error || notice) && <div className={error ? "banner error" : "banner"} role={error ? "alert" : "status"}><span>{error || notice}</span><button className="quiet" aria-label="Закрыть уведомление" onClick={() => { setError(""); setNotice(""); }}>Закрыть</button></div>}
|
||||
<div className="app-content">
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-heading"><h1>Чаты</h1><button className="primary compact" aria-expanded={showCreate} onClick={() => setShowCreate(!showCreate)}>{showCreate ? "Отмена" : "Новый чат"}</button></div>
|
||||
{showCreate && <form className="create-form stack" onSubmit={createChat}>
|
||||
<label>Название<input autoFocus required maxLength={100} value={title} onChange={(event) => setTitle(event.target.value)} /></label>
|
||||
<label>Участники<textarea rows={2} placeholder="ID через запятую · вы уже добавлены" value={members} onChange={(event) => setMembers(event.target.value)} /></label>
|
||||
<button className="primary" disabled={creating}>{creating ? "Создание…" : "Создать"}</button>
|
||||
</form>}
|
||||
<div className="list-toolbar"><span>{chats.items.length} на странице</span><button className="quiet" disabled={chats.busy} onClick={chats.refresh}>Обновить</button></div>
|
||||
<div className="chat-list" aria-busy={chats.busy}>
|
||||
{chats.busy ? <p className="empty-note">Загрузка…</p> : chats.failed ? <p className="empty-note">Не удалось загрузить чаты</p> : !chats.items.length && <p className="empty-note">Нет чатов</p>}
|
||||
{chats.items.map((chat) => <button key={chat.id} className={`chat-item ${chatId === chat.id ? "selected" : ""}`} aria-pressed={chatId === chat.id} disabled={sending} onClick={() => setSelectedChat(chat)}><span className="chat-avatar">{chat.title.slice(0, 1).toUpperCase()}</span><span className="chat-copy"><strong>{chat.title}</strong><small>{chat.member_ids.length} участн.</small></span></button>)}
|
||||
</div>
|
||||
<Pagination label="Чаты" page={chats} />
|
||||
<details className="identity"><summary>Мой ID</summary><code>{user.id}</code><button className="quiet" onClick={() => void copyId()}>Копировать</button></details>
|
||||
</aside>
|
||||
<main className="conversation">
|
||||
{!selectedChat ? <div className="conversation-empty"><svg viewBox="0 0 48 48" aria-hidden="true"><path d="M8 8h32v26H18L8 42V8Z"/><path d="M17 18h14M17 25h9"/></svg><h2>Выберите чат</h2></div> : <>
|
||||
<header className="conversation-header"><div><h2>{selectedChat.title}</h2><details className="members"><summary>{selectedChat.member_ids.length} участн.</summary>{selectedChat.member_ids.map((id) => <code key={id}>{id}{id === user.id ? " · вы" : ""}</code>)}</details></div><button className="quiet" disabled={messages.busy || sending} onClick={messages.reload}>Обновить</button></header>
|
||||
<div className="messages" aria-busy={messages.busy}>
|
||||
{messages.busy ? <p className="empty-note">Загрузка…</p> : messages.failed ? <p className="empty-note">Не удалось загрузить сообщения</p> : !messages.items.length && <p className="empty-note">Нет сообщений</p>}
|
||||
{messages.items.map((message) => <article key={message.id} className={`message ${message.sender_id === user.id ? "own" : ""}`}><div className="message-meta"><strong title={message.sender_id}>{message.sender_id === user.id ? "Вы" : message.sender_id.slice(0, 8)}</strong><time dateTime={message.created_at}>{dateText(message.created_at)}</time></div><p>{message.text}</p></article>)}
|
||||
</div>
|
||||
<Pagination label="Сообщения" page={messages} />
|
||||
<form className="composer" onSubmit={sendMessage}><textarea aria-label="Сообщение" value={drafts[chatId] || ""} onChange={(event) => setDrafts({ ...drafts, [chatId]: event.target.value })} rows={2} maxLength={4000} required placeholder="Сообщение…" /><button className="primary" disabled={sending || messages.busy || !(drafts[chatId] || "").trim()}>{sending ? "Отправка…" : "Отправить"}</button></form>
|
||||
</>}
|
||||
</main>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const [session, setSession] = useState<{ token: string; user: User } | null>(null);
|
||||
const [restoring, setRestoring] = useState(true);
|
||||
const [notice, setNotice] = useState("");
|
||||
const logout = useCallback((message = "") => {
|
||||
sessionStorage.removeItem(tokenKey); setSession(null); setNotice(message);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const token = sessionStorage.getItem(tokenKey);
|
||||
if (!token) { setRestoring(false); return; }
|
||||
let active = true;
|
||||
api.me(token).then((user) => {
|
||||
if (active) setSession({ token, user });
|
||||
}).catch((cause: unknown) => {
|
||||
if (!active) return;
|
||||
sessionStorage.removeItem(tokenKey);
|
||||
setNotice(cause instanceof ApiError && cause.status === 401 ? "Сессия истекла. Войдите снова." : errorText(cause));
|
||||
}).finally(() => { if (active) setRestoring(false); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
|
||||
if (restoring) return <main className="loading-page">Загрузка…</main>;
|
||||
if (session) return <Workspace key={session.token} {...session} onLogout={logout} />;
|
||||
return <><AuthForm onSuccess={(next) => { sessionStorage.setItem(tokenKey, next.token); setSession(next); setNotice(""); }} />{notice && <div className="toast" role="status">{notice}</div>}</>;
|
||||
}
|
||||
<label>
|
||||
Имя пользователя
|
||||
<input value={username} onChange={(event) => setUsername(event.target.value)} required minLength={3} maxLength={32} pattern="[a-z0-9_]+" autoComplete="username" placeholder="ivan_01" />
|
||||
</label>
|
||||
{mode === "register" && (
|
||||
<label>
|
||||
Отображаемое имя
|
||||
<input value={displayName} onChange={(event) => setDisplayName(event.target.value)} required maxLength={100} placeholder="Иван" />
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
Пароль
|
||||
<input type="password" value={password} onChange={(event) => setPassword(event.target.value)} required minLength={12} maxLength={128} autoComplete={mode === "register" ? "new-password" : "current-password"} placeholder="Не менее 12 символов" />
|
||||
</label>
|
||||
{error && <p className="error" role="alert">{error}</p>}
|
||||
<button type="submit" className="primary" disabled={busy}>{busy ? "Подождите…" : mode === "register" ? "Создать аккаунт и войти" : "Войти"}</button>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function Workspace({ token, user, onLogout }: { token: string; user: User; onLogout: (notice?: string) => void }) {
|
||||
const [selectedChat, setSelectedChat] = useState<Chat | null>(null);
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [title, setTitle] = useState("");
|
||||
const [members, setMembers] = useState("");
|
||||
const [drafts, setDrafts] = useState<Record<string, string>>({});
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [sending, setSending] = useState(false);
|
||||
const pendingMessages = useRef<Record<string, { text: string; key: string }>>({});
|
||||
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<HTMLFormElement>) {
|
||||
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<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const text = (drafts[chatId] || "").trim();
|
||||
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("");
|
||||
try {
|
||||
await api.sendMessage(token, chatId, text, pending.key);
|
||||
delete pendingMessages.current[chatId];
|
||||
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 <div className="app-shell">
|
||||
<header className="app-header">
|
||||
<a className="brand" href="/">Мессенджер<span className="brand-dot" /></a>
|
||||
<div className="account"><span className="avatar">{user.display_name.slice(0, 1).toUpperCase()}</span><div><strong>{user.display_name}</strong><small>@{user.username}</small></div><button className="quiet" onClick={() => void logout()}>Выйти</button></div>
|
||||
</header>
|
||||
{(error || notice) && <div className={error ? "banner error" : "banner"} role={error ? "alert" : "status"}><span>{error || notice}</span><button className="quiet" aria-label="Закрыть уведомление" onClick={() => { setError(""); setNotice(""); }}>Закрыть</button></div>}
|
||||
<div className="app-content">
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-heading"><h1>Чаты</h1><button className="primary compact" aria-expanded={showCreate} onClick={() => setShowCreate(!showCreate)}>{showCreate ? "Отмена" : "Новый чат"}</button></div>
|
||||
{showCreate && <form className="create-form stack" onSubmit={createChat}>
|
||||
<label>Название<input autoFocus required maxLength={100} value={title} onChange={(event) => setTitle(event.target.value)} /></label>
|
||||
<label>Участники<textarea rows={2} placeholder="ID через запятую · вы уже добавлены" value={members} onChange={(event) => setMembers(event.target.value)} /></label>
|
||||
<button className="primary" disabled={creating}>{creating ? "Создание…" : "Создать"}</button>
|
||||
</form>}
|
||||
<div className="list-toolbar"><span>{chats.items.length} на странице</span><button className="quiet" disabled={chats.busy} onClick={chats.refresh}>Обновить</button></div>
|
||||
<div className="chat-list" aria-busy={chats.busy}>
|
||||
{chats.busy ? <p className="empty-note">Загрузка…</p> : chats.failed ? <p className="empty-note">Не удалось загрузить чаты</p> : !chats.items.length && <p className="empty-note">Нет чатов</p>}
|
||||
{chats.items.map((chat) => <button key={chat.id} className={`chat-item ${chatId === chat.id ? "selected" : ""}`} aria-pressed={chatId === chat.id} disabled={sending} onClick={() => setSelectedChat(chat)}><span className="chat-avatar">{chat.title.slice(0, 1).toUpperCase()}</span><span className="chat-copy"><strong>{chat.title}</strong><small>{chat.member_ids.length} участн.</small></span></button>)}
|
||||
</div>
|
||||
<Pagination label="Чаты" page={chats} />
|
||||
<details className="identity"><summary>Мой ID</summary><code>{user.id}</code><button className="quiet" onClick={() => void copyId()}>Копировать</button></details>
|
||||
</aside>
|
||||
<main className="conversation">
|
||||
{!selectedChat ? <div className="conversation-empty"><svg viewBox="0 0 48 48" aria-hidden="true"><path d="M8 8h32v26H18L8 42V8Z"/><path d="M17 18h14M17 25h9"/></svg><h2>Выберите чат</h2></div> : <>
|
||||
<header className="conversation-header"><div><h2>{selectedChat.title}</h2><details className="members"><summary>{selectedChat.member_ids.length} участн.</summary>{selectedChat.member_ids.map((id) => <code key={id}>{id}{id === user.id ? " · вы" : ""}</code>)}</details></div><button className="quiet" disabled={messages.busy || sending} onClick={messages.reload}>Обновить</button></header>
|
||||
<div className="messages" aria-busy={messages.busy}>
|
||||
{messages.busy ? <p className="empty-note">Загрузка…</p> : messages.failed ? <p className="empty-note">Не удалось загрузить сообщения</p> : !messages.items.length && <p className="empty-note">Нет сообщений</p>}
|
||||
{messages.items.map((message) => <article key={message.id} className={`message ${message.sender_id === user.id ? "own" : ""}`}><div className="message-meta"><strong title={message.sender_id}>{message.sender_id === user.id ? "Вы" : message.sender_id.slice(0, 8)}</strong><time dateTime={message.created_at}>{dateText(message.created_at)}</time></div><p>{message.text}</p></article>)}
|
||||
</div>
|
||||
<Pagination label="Сообщения" page={messages} />
|
||||
<form className="composer" onSubmit={sendMessage}><textarea aria-label="Сообщение" value={drafts[chatId] || ""} onChange={(event) => setDrafts({ ...drafts, [chatId]: event.target.value })} rows={2} maxLength={4000} required placeholder="Сообщение…" /><button className="primary" disabled={sending || messages.busy || !(drafts[chatId] || "").trim()}>{sending ? "Отправка…" : "Отправить"}</button></form>
|
||||
</>}
|
||||
</main>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const [session, setSession] = useState<{ token: string; user: User } | null>(null);
|
||||
const [restoring, setRestoring] = useState(true);
|
||||
const [notice, setNotice] = useState("");
|
||||
const logout = useCallback((message = "") => {
|
||||
sessionStorage.removeItem(tokenKey); setSession(null); setNotice(message);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const token = sessionStorage.getItem(tokenKey);
|
||||
if (!token) { setRestoring(false); return; }
|
||||
let active = true;
|
||||
api.me(token).then((user) => {
|
||||
if (active) setSession({ token, user });
|
||||
}).catch((cause: unknown) => {
|
||||
if (!active) return;
|
||||
sessionStorage.removeItem(tokenKey);
|
||||
setNotice(cause instanceof ApiError && cause.status === 401 ? "Сессия истекла. Войдите снова." : errorText(cause));
|
||||
}).finally(() => { if (active) setRestoring(false); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
|
||||
if (restoring) return <main className="loading-page">Загрузка…</main>;
|
||||
if (session) return <Workspace key={session.token} {...session} onLogout={logout} />;
|
||||
return <><AuthForm onSuccess={(next) => { sessionStorage.setItem(tokenKey, next.token); setSession(next); setNotice(""); }} />{notice && <div className="toast" role="status">{notice}</div>}</>;
|
||||
}
|
||||
|
||||
@@ -118,10 +118,10 @@ export const api = {
|
||||
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`, {
|
||||
method: "POST",
|
||||
headers: { ...bearer(token), "Content-Type": "application/json" },
|
||||
headers: { ...bearer(token), "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
|
||||
body: JSON.stringify({ text }),
|
||||
}),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user