feat: add direct upload to 5 track
This commit is contained in:
@@ -14,11 +14,13 @@ TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
attachments-cleanup \
|
||||
check validate test load test-persistence test-failover \
|
||||
test-backend test-baseline test-baseline-persistence test-grade3 test-grade3-failures \
|
||||
test-attachment-validation test-attachment-access test-upload-recovery test-attachment-cleanup test-s3-permissions test-upload-memory
|
||||
test-attachment-validation test-attachment-access test-upload-recovery test-attachment-cleanup test-s3-permissions test-upload-memory \
|
||||
test-direct-upload test-direct-upload-validation test-direct-upload-access test-direct-upload-recovery test-direct-upload-cleanup
|
||||
|
||||
|
||||
|
||||
help:
|
||||
@echo "test-direct-upload / test-direct-upload-validation / test-direct-upload-access / test-direct-upload-recovery / test-direct-upload-cleanup"
|
||||
@echo "app-build: build application images; app-up: build and start the full stack"
|
||||
@echo "app-start: start without rebuilding; app-stop: stop and keep containers"
|
||||
@echo "app-down: remove containers and networks, keeping data volumes"
|
||||
@@ -124,3 +126,20 @@ test-s3-permissions: app-init
|
||||
|
||||
test-upload-memory:
|
||||
$(PYTHON) scripts/check_upload_memory.py
|
||||
|
||||
test-direct-upload: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests go test -race -count=1 -v ./backend/tests -run '^TestDirectUploadFlow$$'
|
||||
$(PYTHON) scripts/check_direct_upload.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-direct-upload-validation: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests go test -race -count=1 -v ./backend/tests -run '^TestDirectUploadValidation'
|
||||
|
||||
test-direct-upload-access: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests go test -race -count=1 -v ./backend/tests -run '^TestDirectUploadAccess'
|
||||
|
||||
test-direct-upload-recovery: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests go test -race -count=1 -v ./backend/tests -run '^TestDirectUpload(Recovery|CrashHelper)'
|
||||
$(COMPOSE) exec -T frontend npm run test:direct-upload
|
||||
|
||||
test-direct-upload-cleanup: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests go test -race -count=1 -v ./backend/tests -run '^TestDirectUploadCleanup'
|
||||
|
||||
+6
-1
@@ -56,7 +56,9 @@ services:
|
||||
s3:
|
||||
cpus: 1.0
|
||||
mem_limit: 512m
|
||||
networks: [data]
|
||||
networks: [edge, data]
|
||||
ports:
|
||||
- "127.0.0.1:9000:9000"
|
||||
build:
|
||||
context: ./infra
|
||||
dockerfile: minio.Dockerfile
|
||||
@@ -64,6 +66,7 @@ services:
|
||||
MINIO_ROOT_USER_FILE: /run/secrets/s3_access_key_id
|
||||
MINIO_ROOT_PASSWORD_FILE: /run/secrets/s3_secret_access_key
|
||||
MINIO_BROWSER: "off"
|
||||
MINIO_API_CORS_ALLOW_ORIGIN: ${S3_CORS_ORIGINS:-http://127.0.0.1:5173,http://localhost:5173}
|
||||
volumes:
|
||||
- s3_data:/data
|
||||
- ./secrets/s3_access_key_id:/run/secrets/s3_access_key_id:ro
|
||||
@@ -82,6 +85,7 @@ services:
|
||||
S3_ROOT_ACCESS_KEY_ID_FILE: /run/secrets/s3_root_access_key_id
|
||||
S3_ROOT_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_root_secret_access_key
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000}
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://127.0.0.1:9000}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID_FILE: ${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id}
|
||||
@@ -204,6 +208,7 @@ services:
|
||||
target: builder
|
||||
environment:
|
||||
<<: *s3-environment
|
||||
S3_PUBLIC_ENDPOINT: http://s3:9000
|
||||
TEST_DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
|
||||
TEST_REDIS_ADDR: redis:6379
|
||||
volumes:
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
services:
|
||||
s3:
|
||||
ports: !override []
|
||||
haproxy:
|
||||
ports: !override
|
||||
- "127.0.0.1:18080:8080"
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real presigned POST flow; synthetic data only, never prints signed fields/tokens."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check, run
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(
|
||||
["docker", "compose", *args], cwd=ROOT, text=True, stderr=subprocess.STDOUT
|
||||
)
|
||||
|
||||
|
||||
def upload(c, actor, chat, data, concurrent=True):
|
||||
path = f"/api/v1/chats/{chat['id']}/attachment-uploads"
|
||||
result = c.call("POST", path, 201, actor=actor, body={
|
||||
"filename": "direct.png", "content_type": "image/png",
|
||||
"size_bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(),
|
||||
})
|
||||
instruction = json.loads(result["bytes"])
|
||||
boundary = "direct-" + uuid.uuid4().hex
|
||||
body = bytearray()
|
||||
for key, value in instruction["upload"]["fields"].items():
|
||||
body.extend(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n{value}\r\n'.encode())
|
||||
body.extend(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="direct.png"\r\nContent-Type: image/png\r\n\r\n'.encode())
|
||||
body.extend(data)
|
||||
body.extend(f"\r\n--{boundary}--\r\n".encode())
|
||||
req = urllib.request.Request(instruction["upload"]["url"], data=bytes(body), method="POST", headers={"Content-Type": "multipart/form-data; boundary=" + boundary})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=25) as response:
|
||||
check(response.status == 204, "S3 POST did not return 204")
|
||||
except Exception:
|
||||
raise Failure("S3 POST failed (request details suppressed)") from None
|
||||
endpoint = path + "/" + instruction["upload_id"] + "/complete"
|
||||
if not concurrent:
|
||||
return c.call("POST", endpoint, 201, actor=actor, schema="Attachment"), endpoint
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
futures = [pool.submit(c.call, "POST", endpoint, 201, actor=actor, schema="Attachment") for _ in range(2)]
|
||||
results = [future.result() for future in futures]
|
||||
check(results[0]["json"] == results[1]["json"], "concurrent complete returned different metadata")
|
||||
instances = {r["headers"]["X-Instance-Id"] for r in results}
|
||||
check(len(instances) == 2, "complete did not exercise both API replicas")
|
||||
return results[0], endpoint
|
||||
|
||||
|
||||
def wait_content(c, actor, attachment, data, excluded=None):
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
try:
|
||||
response = c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=actor)
|
||||
check(response["bytes"] == data, "download differs from original")
|
||||
if excluded:
|
||||
check(response["headers"]["X-Instance-Id"] != excluded, "stopped replica served download")
|
||||
return
|
||||
except Failure:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--failures", action="store_true", help="stop each confirming replica in turn, restoring it afterwards")
|
||||
parser.add_argument("--restart", action="store_true", help="restart this lab using scripts/restart.sh")
|
||||
args = parser.parse_args()
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
data = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
confirmed, endpoint = upload(c, alice, chat, data)
|
||||
attachment = confirmed["json"]
|
||||
c.call("GET", f"/api/v1/attachments/{attachment['id']}", 404, actor=eve)
|
||||
wait_content(c, bob, attachment, data)
|
||||
c.message(alice, chat, "", attachments=[attachment["id"]])
|
||||
if args.failures:
|
||||
ids = compose("ps", "-q", "api").splitlines()
|
||||
check(len(ids) == 2, "expected two API replicas")
|
||||
for cid in ids:
|
||||
hostname = json.loads(subprocess.check_output(["docker", "inspect", cid], text=True))[0]["Config"]["Hostname"]
|
||||
# Force complete onto the replica about to stop by stopping its peer.
|
||||
peer = next(other for other in ids if other != cid)
|
||||
try:
|
||||
subprocess.run(["docker", "stop", peer], check=True, stdout=subprocess.DEVNULL)
|
||||
# Wait for HAProxy to mark the stopped peer down.
|
||||
deadline = time.monotonic() + 20
|
||||
while True:
|
||||
try:
|
||||
fresh, _ = upload(c, alice, chat, data, concurrent=False)
|
||||
check(fresh["headers"]["X-Instance-Id"] == hostname, "wrong confirming replica")
|
||||
break
|
||||
except Failure:
|
||||
if time.monotonic() >= deadline: raise
|
||||
time.sleep(0.2)
|
||||
compose("up", "-d", "--no-deps", "--no-build", "--wait", "api")
|
||||
subprocess.run(["docker", "stop", cid], check=True, stdout=subprocess.DEVNULL)
|
||||
wait_content(c, bob, fresh["json"], data, excluded=hostname)
|
||||
print("PASS: original survives stopping confirming replica " + hostname)
|
||||
finally:
|
||||
compose("up", "-d", "--no-deps", "--no-build", "--wait", "api")
|
||||
if args.restart:
|
||||
subprocess.run([str(ROOT / "scripts/restart.sh")], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
||||
wait_content(c, bob, attachment, data)
|
||||
again = c.call("POST", endpoint, 201, actor=alice, schema="Attachment")
|
||||
check(again["json"] == attachment, "restart changed direct complete result")
|
||||
print("PASS: session, direct upload receipt, metadata and bytes survive restart")
|
||||
print("PASS: real S3 form, concurrent complete through two replicas, authorized bytes and attachment-only message")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -22,12 +22,14 @@ def main():
|
||||
if mount["Type"] == "bind"
|
||||
]
|
||||
if service == "s3":
|
||||
assert not info["HostConfig"]["PortBindings"], "S3 ports are published"
|
||||
assert info["HostConfig"]["PortBindings"] == {
|
||||
"9000/tcp": [{"HostIp": "127.0.0.1", "HostPort": "9000"}]
|
||||
}, "only loopback S3 port may be published"
|
||||
assert "MINIO_BROWSER=off" in info["Config"]["Env"], (
|
||||
"MinIO console is enabled"
|
||||
)
|
||||
assert set(info["NetworkSettings"]["Networks"]) == {
|
||||
"highload-lab4_data"
|
||||
"highload-lab4_data", "highload-lab4_edge"
|
||||
}
|
||||
else:
|
||||
assert (
|
||||
@@ -56,7 +58,7 @@ def main():
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / "isolation.json").write_text(json.dumps(evidence, indent=2) + "\n")
|
||||
print(
|
||||
"PASS: private S3 network, disabled console, restricted API mounts, bounded tmpfs"
|
||||
"PASS: loopback-only private S3, disabled console, restricted API mounts, bounded tmpfs"
|
||||
)
|
||||
|
||||
|
||||
|
||||
+3
-1
@@ -26,7 +26,9 @@ def main():
|
||||
POSTGRES_USER="messenger",
|
||||
POSTGRES_PASSWORD=secrets.token_hex(24),
|
||||
)
|
||||
defaults.update(UPLOAD_CLEANUP_GRACE_SECONDS="600", UPLOAD_TMP_DIR="/tmp/uploads")
|
||||
defaults.update(UPLOAD_CLEANUP_GRACE_SECONDS="600", UPLOAD_TMP_DIR="/tmp/uploads",
|
||||
S3_PUBLIC_ENDPOINT="http://127.0.0.1:9000",
|
||||
S3_CORS_ORIGINS="http://127.0.0.1:5173,http://localhost:5173")
|
||||
values = defaults | existing
|
||||
for name, lower, upper in (
|
||||
("APP_PORT", 1, 65535),
|
||||
|
||||
@@ -36,14 +36,18 @@ func runUploadCleanup(args []string) error {
|
||||
for {
|
||||
pass, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
result, err := store.CleanupUploads(pass, *dryRun, objects.Delete)
|
||||
direct, directErr := store.CleanupDirectUploads(pass, *dryRun, objects.Delete)
|
||||
cancel()
|
||||
if encodeErr := json.NewEncoder(os.Stdout).Encode(result); encodeErr != nil {
|
||||
if encodeErr := json.NewEncoder(os.Stdout).Encode(map[string]any{"originals": result, "direct": direct}); encodeErr != nil {
|
||||
return encodeErr
|
||||
}
|
||||
if !*loop {
|
||||
if err == nil {
|
||||
err = directErr
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
if err != nil || directErr != nil {
|
||||
log.Print("upload cleanup pass failed; journal retained for retry")
|
||||
}
|
||||
select {
|
||||
|
||||
@@ -4,8 +4,9 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"messenger/src/backend/services"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type createChatRequest struct {
|
||||
@@ -115,6 +116,10 @@ func chatSubresourceHandler(chats *services.ChatService, messages *services.Mess
|
||||
createMessage := createMessageHandler(chats, messages)
|
||||
listMessages := listMessagesHandler(chats, messages)
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if attachments != nil && strings.Contains(r.URL.Path, "/attachment-uploads") {
|
||||
directUploadHandler(chats, attachments)(w, r)
|
||||
return
|
||||
}
|
||||
if attachments != nil && strings.HasSuffix(r.URL.Path, "/attachments") {
|
||||
uploadAttachmentHandler(chats, attachments)(w, r)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/services"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func directUploadHandler(chats *services.ChatService, attachments *services.AttachmentService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
user, ok := requestUserID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/v1/chats/"), "/")
|
||||
if (len(parts) != 2 && (len(parts) != 4 || parts[3] != "complete")) || parts[1] != "attachment-uploads" {
|
||||
writeError(w, 404, "not_found", "upload endpoint not found", requestID)
|
||||
return
|
||||
}
|
||||
chat, err := uuid.Parse(parts[0])
|
||||
if err != nil {
|
||||
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||
return
|
||||
}
|
||||
if _, err = chats.Get(r.Context(), user, chat.String()); err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
|
||||
defer cancel()
|
||||
if len(parts) == 4 {
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
writeError(w, 400, "invalid_request", "invalid upload id", requestID)
|
||||
return
|
||||
}
|
||||
a, err := attachments.CompleteDirect(ctx, user, chat.String(), id.String())
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 201, a)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||
var input services.DirectUploadInput
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
err = decoder.Decode(&input)
|
||||
if err == nil {
|
||||
var extra any
|
||||
if next := decoder.Decode(&extra); !errors.Is(next, io.EOF) {
|
||||
err = errors.New("expected one JSON object")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, 400, "invalid_request", "invalid upload JSON (maximum 4 KiB)", requestID)
|
||||
return
|
||||
}
|
||||
result, err := attachments.InitDirect(ctx, user, chat.String(), input)
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 201, result)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
@@ -44,6 +45,11 @@ func writeError(w http.ResponseWriter, status int, code, message, requestID stri
|
||||
}
|
||||
|
||||
func writeServiceError(w http.ResponseWriter, err error, requestID string) {
|
||||
var upload repositories.UploadError
|
||||
if errors.As(err, &upload) {
|
||||
writeError(w, upload.Status, upload.Code, upload.Message, requestID)
|
||||
return
|
||||
}
|
||||
var invalid services.InvalidInput
|
||||
switch {
|
||||
case errors.As(err, &invalid):
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *AttachmentStore) CleanupDirectUploads(ctx context.Context, dryRun bool, remove func(context.Context, string) error) (CleanupResult, error) {
|
||||
result := CleanupResult{DryRun: dryRun}
|
||||
rows, err := s.db.Query(ctx, `SELECT id::text FROM direct_uploads WHERE cleanup_after<=clock_timestamp() ORDER BY cleanup_after,id LIMIT 100`)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
ids := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err = rows.Scan(&id); err != nil {
|
||||
rows.Close()
|
||||
return result, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Candidates = len(ids)
|
||||
for _, id := range ids {
|
||||
outcome, err := s.cleanupDirectUpload(ctx, id, dryRun, remove)
|
||||
if err != nil {
|
||||
result.Failed++
|
||||
continue
|
||||
}
|
||||
switch outcome {
|
||||
case "deleted":
|
||||
result.Deleted++
|
||||
case "eligible":
|
||||
result.Eligible++
|
||||
default:
|
||||
result.Skipped++
|
||||
}
|
||||
}
|
||||
if result.Failed > 0 {
|
||||
return result, fmt.Errorf("%d direct upload cleanup operations failed", result.Failed)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentStore) cleanupDirectUpload(ctx context.Context, id string, dryRun bool, remove func(context.Context, string) error) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var key, state string
|
||||
var barrier, complete, purge, now time.Time
|
||||
err = tx.QueryRow(ctx, `SELECT staging_key,state,complete_before+interval '600 seconds',complete_before,purge_after,clock_timestamp() FROM direct_uploads WHERE id=$1 AND cleanup_after<=clock_timestamp() FOR UPDATE SKIP LOCKED`, id).Scan(&key, &state, &barrier, &complete, &purge, &now)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "skipped", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil || key != "staging/direct/"+parsed.String() {
|
||||
return "", errors.New("invalid direct staging key")
|
||||
}
|
||||
if state == "pending" && now.Before(barrier) {
|
||||
return "skipped", nil
|
||||
}
|
||||
if dryRun {
|
||||
return "eligible", nil
|
||||
}
|
||||
if err = remove(ctx, key); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if now.After(purge) && !now.Before(barrier) {
|
||||
_, err = tx.Exec(ctx, `DELETE FROM direct_uploads WHERE id=$1`, id)
|
||||
} else {
|
||||
if state == "pending" && !now.Before(complete) {
|
||||
state = "expired"
|
||||
}
|
||||
// An early cleanup is not final: a still valid POST can recreate staging.
|
||||
// Keep a second cleanup after the safety barrier, then retain the receipt 24h.
|
||||
next := barrier
|
||||
if !now.Before(barrier) {
|
||||
next = purge
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE direct_uploads SET state=$2,cleanup_after=$3 WHERE id=$1`, id, state, next)
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "deleted", nil
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// UploadError is also persisted for terminal validation failures, so retries agree.
|
||||
type UploadError struct {
|
||||
Status int
|
||||
Code, Message string
|
||||
}
|
||||
|
||||
func (e UploadError) Error() string { return e.Message }
|
||||
|
||||
func DirectError(code string) UploadError {
|
||||
switch code {
|
||||
case "upload_not_uploaded":
|
||||
return UploadError{409, code, "file has not been uploaded"}
|
||||
case "upload_expired":
|
||||
return UploadError{409, code, "upload confirmation period has expired"}
|
||||
case "upload_size_mismatch":
|
||||
return UploadError{400, code, "uploaded size differs from declared size"}
|
||||
case "upload_checksum_mismatch":
|
||||
return UploadError{400, code, "uploaded SHA-256 differs from declared checksum"}
|
||||
case "payload_too_large":
|
||||
return UploadError{413, code, "image exceeds upload limits"}
|
||||
default:
|
||||
return UploadError{415, "unsupported_media_type", "a valid PNG or JPEG matching Content-Type is required"}
|
||||
}
|
||||
}
|
||||
|
||||
type DirectUpload struct {
|
||||
ID string `json:"upload_id"`
|
||||
AttachmentID string `json:"-"`
|
||||
OwnerID string `json:"-"`
|
||||
ChatID string `json:"-"`
|
||||
Filename string `json:"-"`
|
||||
ContentType string `json:"-"`
|
||||
SizeBytes int64 `json:"-"`
|
||||
SHA256 string `json:"-"`
|
||||
StagingKey string `json:"-"`
|
||||
FinalKey string `json:"-"`
|
||||
State string `json:"-"`
|
||||
ErrorCode *string `json:"-"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CompleteBefore time.Time `json:"complete_before"`
|
||||
}
|
||||
|
||||
const directColumns = `d.id,d.attachment_id,d.owner_id,d.chat_id,d.filename,d.content_type,d.size_bytes,d.sha256,d.staging_key,d.final_key,d.state,d.error_code,d.expires_at,d.complete_before`
|
||||
|
||||
func scanDirect(row pgx.Row) (DirectUpload, error) {
|
||||
var u DirectUpload
|
||||
err := row.Scan(&u.ID, &u.AttachmentID, &u.OwnerID, &u.ChatID, &u.Filename, &u.ContentType, &u.SizeBytes, &u.SHA256, &u.StagingKey, &u.FinalKey, &u.State, &u.ErrorCode, &u.ExpiresAt, &u.CompleteBefore)
|
||||
return u, err
|
||||
}
|
||||
|
||||
func (s *AttachmentStore) CreateDirect(ctx context.Context, u DirectUpload) (DirectUpload, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
return scanDirect(s.db.QueryRow(ctx, `INSERT INTO direct_uploads AS d(id,attachment_id,owner_id,chat_id,filename,content_type,size_bytes,sha256,staging_key,final_key) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING `+directColumns, u.ID, u.AttachmentID, u.OwnerID, u.ChatID, u.Filename, u.ContentType, u.SizeBytes, u.SHA256, u.StagingKey, u.FinalKey))
|
||||
}
|
||||
|
||||
func (s *AttachmentStore) GetDirect(ctx context.Context, id, chat, user string) (DirectUpload, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
return scanDirect(s.db.QueryRow(ctx, `SELECT `+directColumns+` FROM direct_uploads d JOIN chat_members cm ON cm.chat_id=d.chat_id AND cm.user_id=$3 WHERE d.id=$1 AND d.chat_id=$2 AND d.owner_id=$3`, id, chat, user))
|
||||
}
|
||||
|
||||
// The session lock serializes complete across replicas. A separately committed
|
||||
// reservation survives rollback/crash, while its row lock protects the final key.
|
||||
func (s *AttachmentStore) CompleteDirect(ctx context.Context, id, chat, user string, validate func(context.Context, DirectUpload) error) (Attachment, error) {
|
||||
var a Attachment
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
u, err := scanDirect(tx.QueryRow(ctx, `SELECT `+directColumns+` FROM direct_uploads d JOIN chat_members cm ON cm.chat_id=d.chat_id AND cm.user_id=$3 WHERE d.id=$1 AND d.chat_id=$2 AND d.owner_id=$3 FOR UPDATE OF d`, id, chat, user))
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
if u.StagingKey != "staging/direct/"+u.ID || u.FinalKey != "originals/"+u.AttachmentID {
|
||||
return a, errors.New("invalid direct upload object keys")
|
||||
}
|
||||
if u.State == "ready" {
|
||||
return s.GetForMember(ctx, u.AttachmentID, user)
|
||||
}
|
||||
if u.State == "rejected" && u.ErrorCode != nil {
|
||||
return a, DirectError(*u.ErrorCode)
|
||||
}
|
||||
var expired bool
|
||||
if err = tx.QueryRow(ctx, `SELECT clock_timestamp()>=$1`, u.CompleteBefore).Scan(&expired); err != nil {
|
||||
return a, err
|
||||
}
|
||||
if expired || u.State == "expired" {
|
||||
return a, DirectError("upload_expired")
|
||||
}
|
||||
grace, err := UploadCleanupGrace()
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
// ON CONFLICT handles retry after an interrupted COPY without losing tracking.
|
||||
_, err = s.db.Exec(ctx, `INSERT INTO upload_attempts(id,object_key,cleanup_after) VALUES($1,$2,clock_timestamp()+$3*interval '1 second') ON CONFLICT(id) DO UPDATE SET cleanup_after=GREATEST(upload_attempts.cleanup_after,EXCLUDED.cleanup_after) WHERE upload_attempts.object_key=EXCLUDED.object_key`, u.AttachmentID, u.FinalKey, grace.Seconds())
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
var key string
|
||||
if err = tx.QueryRow(ctx, `SELECT object_key FROM upload_attempts WHERE id=$1 AND cleanup_after>clock_timestamp() FOR UPDATE`, u.AttachmentID).Scan(&key); err != nil {
|
||||
return a, err
|
||||
}
|
||||
if key != u.FinalKey {
|
||||
return a, errors.New("direct upload reservation mismatch")
|
||||
}
|
||||
if err = validate(ctx, u); err != nil {
|
||||
var invalid UploadError
|
||||
if errors.As(err, &invalid) && (invalid.Status == 400 || invalid.Status == 413 || invalid.Status == 415) {
|
||||
_, saveErr := tx.Exec(ctx, `UPDATE direct_uploads SET state='rejected',error_code=$2,cleanup_after=clock_timestamp(),purge_after=clock_timestamp()+interval '24 hours' WHERE id=$1`, id, invalid.Code)
|
||||
if saveErr != nil {
|
||||
return a, saveErr
|
||||
}
|
||||
if saveErr = tx.Commit(ctx); saveErr != nil {
|
||||
return a, saveErr
|
||||
}
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
a = Attachment{ID: u.AttachmentID, ChatID: u.ChatID, OwnerID: u.OwnerID, Filename: u.Filename, ContentType: u.ContentType, SizeBytes: u.SizeBytes, SHA256: u.SHA256, ObjectKey: u.FinalKey, Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ObjectKey, a.ContentType, a.SizeBytes, a.SHA256, a.CreatedAt, a.UpdatedAt)
|
||||
if err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE direct_uploads SET state='ready',cleanup_after=clock_timestamp(),purge_after=clock_timestamp()+interval '24 hours' WHERE id=$1`, id); err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `DELETE FROM upload_attempts WHERE id=$1`, a.ID); err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE direct_uploads;
|
||||
@@ -0,0 +1,20 @@
|
||||
CREATE TABLE direct_uploads (
|
||||
id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL UNIQUE,
|
||||
owner_id uuid NOT NULL REFERENCES users(id),
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
filename text NOT NULL,
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png','image/jpeg')),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
staging_key text NOT NULL UNIQUE,
|
||||
final_key text NOT NULL UNIQUE,
|
||||
state text NOT NULL DEFAULT 'pending' CHECK (state IN ('pending','ready','rejected','expired')),
|
||||
error_code text,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
expires_at timestamptz NOT NULL DEFAULT clock_timestamp()+interval '120 seconds',
|
||||
complete_before timestamptz NOT NULL DEFAULT clock_timestamp()+interval '720 seconds',
|
||||
cleanup_after timestamptz NOT NULL DEFAULT clock_timestamp()+interval '1320 seconds',
|
||||
purge_after timestamptz NOT NULL DEFAULT clock_timestamp()+interval '24 hours'
|
||||
);
|
||||
CREATE INDEX direct_uploads_cleanup_idx ON direct_uploads(cleanup_after,id);
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
madmin "github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"github.com/minio/minio-go/v7/pkg/lifecycle"
|
||||
)
|
||||
|
||||
func readS3Secret(name string) (string, error) {
|
||||
@@ -58,13 +59,16 @@ func BootstrapS3(ctx context.Context) error {
|
||||
if err = store.Bootstrap(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = bootstrapDirectLifecycle(ctx, client, store.bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
admin, err := madmin.New(endpoint.Host, rootAccess, rootSecret, endpoint.Scheme == "https")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
policy := map[string]any{"Version": "2012-10-17", "Statement": []any{
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetBucketLocation", "s3:ListBucket"}, "Resource": []string{"arn:aws:s3:::" + store.bucket}},
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetObject", "s3:PutObject", "s3:DeleteObject"}, "Resource": []string{"arn:aws:s3:::" + store.bucket + "/originals/*"}},
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetObject", "s3:PutObject", "s3:DeleteObject"}, "Resource": []string{"arn:aws:s3:::" + store.bucket + "/originals/*", "arn:aws:s3:::" + store.bucket + "/staging/direct/*"}},
|
||||
}}
|
||||
data, err := json.Marshal(policy)
|
||||
if err != nil {
|
||||
@@ -81,3 +85,23 @@ func BootstrapS3(ctx context.Context) error {
|
||||
// This idempotent API is supported by our pinned MinIO server release.
|
||||
return admin.SetPolicy(ctx, name, access, false)
|
||||
}
|
||||
|
||||
func bootstrapDirectLifecycle(ctx context.Context, client *minio.Client, bucket string) error {
|
||||
config, err := client.GetBucketLifecycle(ctx, bucket)
|
||||
if err != nil && minio.ToErrorResponse(err).Code != "NoSuchLifecycleConfiguration" {
|
||||
return err
|
||||
}
|
||||
if config == nil {
|
||||
config = lifecycle.NewConfiguration()
|
||||
}
|
||||
const id = "messenger-direct-staging-expiration"
|
||||
rules := make([]lifecycle.Rule, 0, len(config.Rules)+1)
|
||||
for _, rule := range config.Rules {
|
||||
if rule.ID != id {
|
||||
rules = append(rules, rule)
|
||||
}
|
||||
}
|
||||
rules = append(rules, lifecycle.Rule{ID: id, Status: "Enabled", RuleFilter: lifecycle.Filter{Prefix: "staging/direct/"}, Expiration: lifecycle.Expiration{Days: 1}})
|
||||
config.Rules = rules
|
||||
return client.SetBucketLifecycle(ctx, bucket, config)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/url"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
type PostUpload struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Fields map[string]string `json:"fields"`
|
||||
}
|
||||
|
||||
type StoredObject struct {
|
||||
Size int64
|
||||
ETag string
|
||||
}
|
||||
|
||||
func IsObjectMissing(err error) bool {
|
||||
code := minio.ToErrorResponse(err).Code
|
||||
return code == "NoSuchKey" || code == "NoSuchObject" || code == "NotFound"
|
||||
}
|
||||
|
||||
func (s *ObjectStore) PresignDirect(ctx context.Context, key, mime string, size int64, expires time.Time) (PostUpload, error) {
|
||||
endpoint, err := url.Parse(os.Getenv("S3_PUBLIC_ENDPOINT"))
|
||||
if err != nil || endpoint.Host == "" || (endpoint.Scheme != "http" && endpoint.Scheme != "https") || endpoint.Path != "" || endpoint.RawQuery != "" || endpoint.User != nil {
|
||||
return PostUpload{}, errors.New("invalid S3_PUBLIC_ENDPOINT")
|
||||
}
|
||||
access, err := readS3Secret("S3_ACCESS_KEY_ID_FILE")
|
||||
if err != nil {
|
||||
return PostUpload{}, err
|
||||
}
|
||||
secret, err := readS3Secret("S3_SECRET_ACCESS_KEY_FILE")
|
||||
if err != nil {
|
||||
return PostUpload{}, err
|
||||
}
|
||||
signer, err := minio.New(endpoint.Host, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: endpoint.Scheme == "https", Region: os.Getenv("S3_REGION"), BucketLookup: minio.BucketLookupPath})
|
||||
if err != nil {
|
||||
return PostUpload{}, err
|
||||
}
|
||||
policy := minio.NewPostPolicy()
|
||||
for _, err = range []error{policy.SetBucket(s.bucket), policy.SetKey(key), policy.SetExpires(expires), policy.SetContentType(mime), policy.SetContentLengthRange(size, size), policy.SetSuccessStatusAction("204")} {
|
||||
if err != nil {
|
||||
return PostUpload{}, err
|
||||
}
|
||||
}
|
||||
target, fields, err := signer.PresignedPostPolicy(ctx, policy)
|
||||
if err != nil {
|
||||
return PostUpload{}, errors.New("cannot sign upload policy")
|
||||
}
|
||||
return PostUpload{Method: "POST", URL: target.String(), Fields: fields}, nil
|
||||
}
|
||||
|
||||
func (s *ObjectStore) Stat(ctx context.Context, key string) (StoredObject, error) {
|
||||
object, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||
return StoredObject{Size: object.Size, ETag: object.ETag}, err
|
||||
}
|
||||
|
||||
func (s *ObjectStore) Copy(ctx context.Context, source, destination, etag string) error {
|
||||
_, err := s.client.CopyObject(ctx, minio.CopyDestOptions{Bucket: s.bucket, Object: destination}, minio.CopySrcOptions{Bucket: s.bucket, Object: source, MatchETag: etag})
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type DirectUploadInput struct {
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type DirectUploadResponse struct {
|
||||
repositories.DirectUpload
|
||||
Upload repositories.PostUpload `json:"upload"`
|
||||
}
|
||||
|
||||
type DirectObjects interface {
|
||||
AttachmentObjects
|
||||
PresignDirect(context.Context, string, string, int64, time.Time) (repositories.PostUpload, error)
|
||||
Stat(context.Context, string) (repositories.StoredObject, error)
|
||||
Copy(context.Context, string, string, string) error
|
||||
}
|
||||
|
||||
var checksumPattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
|
||||
|
||||
func (s *AttachmentService) InitDirect(ctx context.Context, user, chat string, input DirectUploadInput) (DirectUploadResponse, error) {
|
||||
if err := ValidateFilename(input.Filename); err != nil {
|
||||
return DirectUploadResponse{}, err
|
||||
}
|
||||
if input.ContentType != "image/png" && input.ContentType != "image/jpeg" {
|
||||
return DirectUploadResponse{}, ErrUnsupportedMedia
|
||||
}
|
||||
if input.SizeBytes > MaxUploadBytes {
|
||||
return DirectUploadResponse{}, ErrPayloadTooLarge
|
||||
}
|
||||
if input.SizeBytes < 1 || !checksumPattern.MatchString(input.SHA256) {
|
||||
return DirectUploadResponse{}, InvalidInput{"size must be positive and sha256 must contain 64 lowercase hex characters"}
|
||||
}
|
||||
objects, ok := s.objects.(DirectObjects)
|
||||
if !ok {
|
||||
return DirectUploadResponse{}, errors.New("direct uploads unavailable")
|
||||
}
|
||||
id, attachment := uuid.NewString(), uuid.NewString()
|
||||
u, err := s.metadata.CreateDirect(ctx, repositories.DirectUpload{ID: id, AttachmentID: attachment, OwnerID: user, ChatID: chat, Filename: input.Filename, ContentType: input.ContentType, SizeBytes: input.SizeBytes, SHA256: input.SHA256, StagingKey: "staging/direct/" + id, FinalKey: "originals/" + attachment})
|
||||
if err != nil {
|
||||
return DirectUploadResponse{}, err
|
||||
}
|
||||
post, err := objects.PresignDirect(ctx, u.StagingKey, u.ContentType, u.SizeBytes, u.ExpiresAt)
|
||||
return DirectUploadResponse{DirectUpload: u, Upload: post}, err
|
||||
}
|
||||
|
||||
func (s *AttachmentService) CompleteDirect(ctx context.Context, user, chat, id string) (repositories.Attachment, error) {
|
||||
u, err := s.metadata.GetDirect(ctx, id, chat, user)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return repositories.Attachment{}, ErrAttachmentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
if u.State == "ready" {
|
||||
return s.Get(ctx, u.AttachmentID, user)
|
||||
}
|
||||
objects, ok := s.objects.(DirectObjects)
|
||||
if !ok {
|
||||
return repositories.Attachment{}, errors.New("direct uploads unavailable")
|
||||
}
|
||||
select {
|
||||
case s.uploadSlot <- struct{}{}:
|
||||
defer func() { <-s.uploadSlot }()
|
||||
case <-ctx.Done():
|
||||
return repositories.Attachment{}, ctx.Err()
|
||||
}
|
||||
a, err := s.metadata.CompleteDirect(ctx, id, chat, user, func(ctx context.Context, u repositories.DirectUpload) error {
|
||||
info, err := objects.Stat(ctx, u.StagingKey)
|
||||
if repositories.IsObjectMissing(err) {
|
||||
return repositories.DirectError("upload_not_uploaded")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Size > MaxUploadBytes {
|
||||
return repositories.DirectError("payload_too_large")
|
||||
}
|
||||
if info.Size != u.SizeBytes {
|
||||
return repositories.DirectError("upload_size_mismatch")
|
||||
}
|
||||
// A signed staging key remains writable until expiry. Validate the isolated
|
||||
// final object, never a staging object that can change after validation.
|
||||
if err = objects.Copy(ctx, u.StagingKey, u.FinalKey, info.ETag); err != nil {
|
||||
return err
|
||||
}
|
||||
reader, err := objects.Get(ctx, u.FinalKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
file, err := os.CreateTemp(os.Getenv("UPLOAD_TMP_DIR"), "direct-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
if err = os.Remove(file.Name()); err != nil {
|
||||
return err
|
||||
}
|
||||
hash := sha256.New()
|
||||
size, err := io.CopyBuffer(io.MultiWriter(file, hash), io.LimitReader(reader, MaxUploadBytes+1), make([]byte, 32*1024))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if size > MaxUploadBytes {
|
||||
return repositories.DirectError("payload_too_large")
|
||||
}
|
||||
if size != u.SizeBytes {
|
||||
return repositories.DirectError("upload_size_mismatch")
|
||||
}
|
||||
if hex.EncodeToString(hash.Sum(nil)) != u.SHA256 {
|
||||
return repositories.DirectError("upload_checksum_mismatch")
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = file.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = ValidateImageReader(file, u.ContentType)
|
||||
if errors.Is(err, ErrPayloadTooLarge) {
|
||||
return repositories.DirectError("payload_too_large")
|
||||
}
|
||||
if errors.Is(err, ErrUnsupportedMedia) {
|
||||
return repositories.DirectError("unsupported_media_type")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Err()
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return a, ErrAttachmentNotFound
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
func TestDirectUploadCleanupSafetyAndReplay(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
ctx := context.Background()
|
||||
data := uploadPNG(t)
|
||||
fresh, _ := beginDirect(t, f, store, objects, user, chat, data, "image/png")
|
||||
expired, _ := beginDirect(t, f, store, objects, user, chat, data, "image/png")
|
||||
locked, _ := beginDirect(t, f, store, objects, user, chat, data, "image/png")
|
||||
ready, service := beginDirect(t, f, store, objects, user, chat, data, "image/png")
|
||||
for _, u := range []string{fresh.ID, expired.ID, locked.ID, ready.ID} {
|
||||
record, err := store.GetDirect(ctx, u, chat, user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = objects.Put(ctx, record.StagingKey, bytes.NewReader(data), int64(len(data)), "image/png"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
a, err := service.CompleteDirect(ctx, user, chat, ready.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = f.db.Exec(ctx, `UPDATE direct_uploads SET complete_before=clock_timestamp()-interval '601 seconds',cleanup_after=clock_timestamp()-interval '1 second' WHERE id=ANY($1::uuid[])`, []string{expired.ID, locked.ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tx, err := f.db.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err = tx.Exec(ctx, `SELECT id FROM direct_uploads WHERE id=$1 FOR UPDATE`, locked.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dry, err := store.CleanupDirectUploads(ctx, true, objects.Delete)
|
||||
if err != nil || dry.Eligible != 2 || dry.Deleted != 0 || dry.Skipped != 1 {
|
||||
t.Fatalf("dry: %+v %v", dry, err)
|
||||
}
|
||||
result, err := store.CleanupDirectUploads(ctx, false, objects.Delete)
|
||||
if err != nil || result.Deleted != 2 || result.Skipped != 1 {
|
||||
t.Fatalf("cleanup: %+v %v", result, err)
|
||||
}
|
||||
for _, id := range []string{fresh.ID, locked.ID} {
|
||||
u, _ := store.GetDirect(ctx, id, chat, user)
|
||||
if _, err = objects.Stat(ctx, u.StagingKey); err != nil {
|
||||
t.Fatal("fresh/locked staging removed", err)
|
||||
}
|
||||
}
|
||||
for _, id := range []string{ready.ID, expired.ID} {
|
||||
u, _ := store.GetDirect(ctx, id, chat, user)
|
||||
if _, err = objects.Stat(ctx, u.StagingKey); !repositories.IsObjectMissing(err) {
|
||||
t.Fatal("eligible staging remains", err)
|
||||
}
|
||||
}
|
||||
if _, err = objects.Stat(ctx, a.ObjectKey); err != nil {
|
||||
t.Fatal("ready original removed", err)
|
||||
}
|
||||
// A valid form can recreate staging after early cleanup. The receipt persists.
|
||||
if postDirect(t, ready.Upload, data, nil) != 204 {
|
||||
t.Fatal("replay failed")
|
||||
}
|
||||
if _, err = f.db.Exec(ctx, `UPDATE direct_uploads SET complete_before=clock_timestamp()-interval '601 seconds',cleanup_after=clock_timestamp()-interval '1 second' WHERE id=$1`, ready.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := store.CleanupDirectUploads(ctx, false, objects.Delete)
|
||||
if err != nil || again.Deleted != 1 {
|
||||
t.Fatalf("replay cleanup: %+v %v", again, err)
|
||||
}
|
||||
u, _ := store.GetDirect(ctx, ready.ID, chat, user)
|
||||
if _, err = objects.Stat(ctx, u.StagingKey); !repositories.IsObjectMissing(err) {
|
||||
t.Fatal("replayed staging remains")
|
||||
}
|
||||
same, err := service.CompleteDirect(ctx, user, chat, ready.ID)
|
||||
if err != nil || same.ID != a.ID {
|
||||
t.Fatal("cleanup broke idempotent complete", err)
|
||||
}
|
||||
tx.Rollback(ctx)
|
||||
if _, err = f.db.Exec(ctx, `UPDATE direct_uploads SET purge_after=clock_timestamp()-interval '1 second',cleanup_after=clock_timestamp()-interval '1 second' WHERE id=$1`, ready.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = store.CleanupDirectUploads(ctx, false, objects.Delete); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = objects.Stat(ctx, a.ObjectKey); err != nil {
|
||||
t.Fatal("receipt purge removed final", err)
|
||||
}
|
||||
if _, err = store.GetForMember(ctx, a.ID, user); err != nil {
|
||||
t.Fatal("receipt purge removed metadata", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectUploadCleanupDependencyFailureAndMalformedKey(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
ctx := context.Background()
|
||||
data := uploadPNG(t)
|
||||
result, _ := beginDirect(t, f, store, objects, user, chat, data, "image/png")
|
||||
u, _ := store.GetDirect(ctx, result.ID, chat, user)
|
||||
if err := objects.Put(ctx, u.StagingKey, bytes.NewReader(data), int64(len(data)), "image/png"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.db.Exec(ctx, `UPDATE direct_uploads SET complete_before=clock_timestamp()-interval '601 seconds',cleanup_after=clock_timestamp()-interval '1 second' WHERE id=$1`, result.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failed, err := store.CleanupDirectUploads(ctx, false, func(context.Context, string) error { return errors.New("S3 unavailable") })
|
||||
if err == nil || failed.Failed != 1 {
|
||||
t.Fatal("failed DELETE was lost")
|
||||
}
|
||||
if _, err = objects.Stat(ctx, u.StagingKey); err != nil {
|
||||
t.Fatal("staging changed on failed DELETE", err)
|
||||
}
|
||||
cancelled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if _, err = store.CleanupDirectUploads(cancelled, false, objects.Delete); err == nil {
|
||||
t.Fatal("DB cancellation ignored")
|
||||
}
|
||||
if _, err = f.db.Exec(ctx, `UPDATE direct_uploads SET staging_key=$2 WHERE id=$1`, result.ID, "originals/"+u.AttachmentID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
called := false
|
||||
failed, err = store.CleanupDirectUploads(ctx, false, func(context.Context, string) error { called = true; return nil })
|
||||
if err == nil || failed.Failed != 1 || called {
|
||||
t.Fatal("malformed key reached S3 DELETE")
|
||||
}
|
||||
if _, err = f.db.Exec(ctx, `UPDATE direct_uploads SET staging_key=$2 WHERE id=$1`, result.ID, u.StagingKey); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
retried, err := store.CleanupDirectUploads(ctx, false, objects.Delete)
|
||||
if err != nil || retried.Deleted != 1 {
|
||||
t.Fatalf("retry: %+v %v", retried, err)
|
||||
}
|
||||
repeated, err := store.CleanupDirectUploads(ctx, false, objects.Delete)
|
||||
if err != nil || repeated.Deleted != 0 {
|
||||
t.Fatalf("repeat: %+v %v", repeated, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/lifecycle"
|
||||
)
|
||||
|
||||
func TestDirectUploadAccessPermissionsAndLifecycle(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
root := s3Client(t, true, false)
|
||||
app := s3Client(t, false, false)
|
||||
anon := s3Client(t, false, true)
|
||||
bucket := os.Getenv("S3_BUCKET")
|
||||
key := "staging/direct/" + uuid.NewString()
|
||||
t.Cleanup(func() { root.RemoveObject(ctx, bucket, key, minio.RemoveObjectOptions{}) })
|
||||
if _, err := app.PutObject(ctx, bucket, key, bytes.NewReader([]byte("x")), 1, minio.PutObjectOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
object, err := anon.GetObject(ctx, bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = object.Stat()
|
||||
object.Close()
|
||||
denied(t, err)
|
||||
_, err = app.PutObject(ctx, bucket, "staging/forbidden/"+uuid.NewString(), bytes.NewReader([]byte("x")), 1, minio.PutObjectOptions{})
|
||||
denied(t, err)
|
||||
config, err := root.GetBucketLifecycle(ctx, bucket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Add only our own harmless prefix rule, verify bootstrap merges rather than replaces.
|
||||
ruleID := "direct-test-" + uuid.NewString()
|
||||
config.Rules = append(config.Rules, lifecycle.Rule{ID: ruleID, Status: "Enabled", RuleFilter: lifecycle.Filter{Prefix: "test-lifecycle/" + ruleID + "/"}, Expiration: lifecycle.Expiration{Days: 7}})
|
||||
if err = root.SetBucketLifecycle(ctx, bucket, config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
c, e := root.GetBucketLifecycle(ctx, bucket)
|
||||
if e != nil {
|
||||
t.Error(e)
|
||||
return
|
||||
}
|
||||
rules := []lifecycle.Rule{}
|
||||
for _, r := range c.Rules {
|
||||
if r.ID != ruleID {
|
||||
rules = append(rules, r)
|
||||
}
|
||||
}
|
||||
c.Rules = rules
|
||||
if e = root.SetBucketLifecycle(ctx, bucket, c); e != nil {
|
||||
t.Error(e)
|
||||
}
|
||||
})
|
||||
for i := 0; i < 2; i++ {
|
||||
if err = repositories.BootstrapS3(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
config, err = root.GetBucketLifecycle(ctx, bucket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
managed, preserved := 0, false
|
||||
for _, r := range config.Rules {
|
||||
if r.ID == ruleID {
|
||||
preserved = true
|
||||
}
|
||||
if r.ID == "messenger-direct-staging-expiration" {
|
||||
managed++
|
||||
if r.RuleFilter.Prefix != "staging/direct/" || r.Expiration.Days != 1 || r.Status != "Enabled" {
|
||||
t.Fatal("unsafe staging lifecycle rule")
|
||||
}
|
||||
}
|
||||
}
|
||||
if managed != 1 || !preserved {
|
||||
t.Fatal("bootstrap is not an idempotent lifecycle merge")
|
||||
}
|
||||
denied(t, app.SetBucketLifecycle(ctx, bucket, config))
|
||||
}
|
||||
|
||||
func TestDirectUploadAccessCORS(t *testing.T) {
|
||||
if os.Getenv("S3_ENDPOINT") == "" {
|
||||
t.Skip("S3 integration")
|
||||
}
|
||||
for _, sample := range []struct {
|
||||
origin string
|
||||
allowed bool
|
||||
}{{"http://127.0.0.1:5173", true}, {"http://localhost:5173", true}, {"https://untrusted.example", false}} {
|
||||
request, err := http.NewRequest("OPTIONS", os.Getenv("S3_ENDPOINT")+"/"+os.Getenv("S3_BUCKET"), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.Header.Set("Origin", sample.origin)
|
||||
request.Header.Set("Access-Control-Request-Method", "POST")
|
||||
request.Header.Set("Access-Control-Request-Headers", "content-type")
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
allowed := response.Header.Get("Access-Control-Allow-Origin") == sample.origin
|
||||
if allowed != sample.allowed || response.Header.Get("Access-Control-Allow-Origin") == "*" {
|
||||
t.Fatalf("unexpected CORS allowance for %s", sample.origin)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func directInput(data []byte, mime string) services.DirectUploadInput {
|
||||
sum := sha256.Sum256(data)
|
||||
return services.DirectUploadInput{Filename: "direct.png", ContentType: mime, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:])}
|
||||
}
|
||||
|
||||
func beginDirect(t *testing.T, f *testFixture, store *repositories.AttachmentStore, objects *repositories.ObjectStore, user, chat string, data []byte, mime string) (services.DirectUploadResponse, *services.AttachmentService) {
|
||||
t.Helper()
|
||||
t.Setenv("S3_PUBLIC_ENDPOINT", os.Getenv("S3_ENDPOINT"))
|
||||
service := services.NewAttachmentService(store, objects)
|
||||
result, err := service.InitDirect(context.Background(), user, chat, directInput(data, mime))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rememberDirect(t, store, objects, result.ID, chat, user)
|
||||
return result, service
|
||||
}
|
||||
|
||||
func rememberDirect(t *testing.T, store *repositories.AttachmentStore, objects *repositories.ObjectStore, id, chat, user string) {
|
||||
t.Helper()
|
||||
u, err := store.GetDirect(context.Background(), id, chat, user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
objects.Delete(context.Background(), u.StagingKey)
|
||||
objects.Delete(context.Background(), u.FinalKey)
|
||||
})
|
||||
}
|
||||
|
||||
func postDirect(t *testing.T, p repositories.PostUpload, data []byte, change func(map[string]string)) int {
|
||||
t.Helper()
|
||||
fields := map[string]string{}
|
||||
for k, v := range p.Fields {
|
||||
fields[k] = v
|
||||
}
|
||||
if change != nil {
|
||||
change(fields)
|
||||
}
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
for k, v := range fields {
|
||||
if err := writer.WriteField(k, v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
file, err := writer.CreateFormFile("file", "image.png")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = file.Write(data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req, err := http.NewRequest("POST", p.URL, &body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
client := http.Client{Timeout: 10 * time.Second}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal("S3 form request failed")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
io.Copy(io.Discard, response.Body)
|
||||
return response.StatusCode
|
||||
}
|
||||
|
||||
func requireDirectError(t *testing.T, err error, status int, code string) {
|
||||
t.Helper()
|
||||
var e repositories.UploadError
|
||||
if !errors.As(err, &e) || e.Status != status || e.Code != code {
|
||||
t.Fatalf("expected %d %s, got %v", status, code, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectUploadFlow(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
png := append(uploadPNG(t), []byte("aaaa")...)
|
||||
var jpg bytes.Buffer
|
||||
if err := jpeg.Encode(&jpg, image.NewRGBA(image.Rect(0, 0, 8, 8)), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, sample := range []struct {
|
||||
data []byte
|
||||
mime string
|
||||
}{{png, "image/png"}, {jpg.Bytes(), "image/jpeg"}} {
|
||||
result, service := beginDirect(t, f, store, objects, user, chat, sample.data, sample.mime)
|
||||
if result.ExpiresAt.Sub(time.Now()) > 121*time.Second || result.CompleteBefore.Sub(result.ExpiresAt) < 599*time.Second {
|
||||
t.Fatal("wrong upload deadlines")
|
||||
}
|
||||
if status := postDirect(t, result.Upload, sample.data, nil); status != 204 {
|
||||
t.Fatalf("POST: %d", status)
|
||||
}
|
||||
a, err := service.CompleteDirect(context.Background(), user, chat, result.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
router := attachmentRouter(f, objects)
|
||||
content := attachmentCall(t, f, router, "GET", "/api/v1/attachments/"+a.ID+"/content", user, "", nil, 200)
|
||||
if !bytes.Equal(content.Body.Bytes(), sample.data) {
|
||||
t.Fatal("original bytes changed")
|
||||
}
|
||||
message := []byte(`{"text":"","attachment_ids":["` + a.ID + `"]}`)
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+chat+"/messages", user, "application/json", message, 201)
|
||||
// Lost success response is represented by ignoring a, then asking another service.
|
||||
again, err := services.NewAttachmentService(store, objects).CompleteDirect(context.Background(), user, chat, result.ID)
|
||||
if err != nil || again.ID != a.ID || !again.CreatedAt.Equal(a.CreatedAt) {
|
||||
t.Fatal("complete is not idempotent", err)
|
||||
}
|
||||
replacement := append([]byte(nil), sample.data...)
|
||||
replacement[len(replacement)-1] ^= 1
|
||||
if status := postDirect(t, result.Upload, replacement, nil); status != 204 {
|
||||
t.Fatal("expected valid staging replay")
|
||||
}
|
||||
final, err := objects.Get(context.Background(), a.ObjectKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original, err := io.ReadAll(final)
|
||||
final.Close()
|
||||
if err != nil || !bytes.Equal(original, sample.data) {
|
||||
t.Fatal("staging replay modified final")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectUploadValidationHTTP(t *testing.T) {
|
||||
f, _, objects, user, chat := uploadFixture(t)
|
||||
t.Setenv("S3_PUBLIC_ENDPOINT", os.Getenv("S3_ENDPOINT"))
|
||||
router := attachmentRouter(f, objects)
|
||||
path := "/api/v1/chats/" + chat + "/attachment-uploads"
|
||||
input := directInput(uploadPNG(t), "image/png")
|
||||
valid, _ := json.Marshal(input)
|
||||
for _, sample := range []struct {
|
||||
body []byte
|
||||
status int
|
||||
}{
|
||||
{[]byte(`null`), 400}, {[]byte(`{}`), 400}, {append(append([]byte(nil), valid...), []byte(` {}`)...), 400},
|
||||
{[]byte(strings.Repeat("x", 4097)), 400}, {[]byte(`{"filename":"x","size_bytes":1.5}`), 400},
|
||||
} {
|
||||
attachmentCall(t, f, router, "POST", path, user, "application/json", sample.body, sample.status)
|
||||
}
|
||||
for _, sample := range []struct {
|
||||
mutate func(*services.DirectUploadInput)
|
||||
status int
|
||||
}{
|
||||
{func(i *services.DirectUploadInput) { i.Filename = "../image.png" }, 400},
|
||||
{func(i *services.DirectUploadInput) { i.SHA256 = "invalid" }, 400},
|
||||
{func(i *services.DirectUploadInput) { i.SizeBytes = 0 }, 400},
|
||||
{func(i *services.DirectUploadInput) { i.SizeBytes = 10485761 }, 413},
|
||||
{func(i *services.DirectUploadInput) { i.ContentType = "text/plain" }, 415},
|
||||
} {
|
||||
i := input
|
||||
sample.mutate(&i)
|
||||
body, _ := json.Marshal(i)
|
||||
attachmentCall(t, f, router, "POST", path, user, "application/json", body, sample.status)
|
||||
}
|
||||
store := repositories.NewAttachmentStore(f.db)
|
||||
w := attachmentCall(t, f, router, "POST", path, user, "application/json", valid, 201)
|
||||
var result services.DirectUploadResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rememberDirect(t, store, objects, result.ID, chat, user)
|
||||
if status := postDirect(t, result.Upload, uploadPNG(t), nil); status != 204 {
|
||||
t.Fatal("HTTP-created form failed")
|
||||
}
|
||||
attachmentCall(t, f, router, "POST", path+"/"+result.ID+"/complete", user, "", nil, 201)
|
||||
}
|
||||
|
||||
func TestDirectUploadValidationContents(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
png := uploadPNG(t)
|
||||
huge := append([]byte(nil), png...)
|
||||
binary.BigEndian.PutUint32(huge[16:20], 10001)
|
||||
binary.BigEndian.PutUint32(huge[20:24], 4000)
|
||||
binary.BigEndian.PutUint32(huge[29:33], crc32.ChecksumIEEE(huge[12:29]))
|
||||
for _, sample := range []struct {
|
||||
data []byte
|
||||
mime, code string
|
||||
status int
|
||||
}{
|
||||
{png[:40], "image/png", "unsupported_media_type", 415},
|
||||
{png, "image/jpeg", "unsupported_media_type", 415},
|
||||
{huge, "image/png", "payload_too_large", 413},
|
||||
} {
|
||||
result, service := beginDirect(t, f, store, objects, user, chat, sample.data, sample.mime)
|
||||
if postDirect(t, result.Upload, sample.data, nil) != 204 {
|
||||
t.Fatal("S3 refused matching declared policy")
|
||||
}
|
||||
_, err := service.CompleteDirect(context.Background(), user, chat, result.ID)
|
||||
requireDirectError(t, err, sample.status, sample.code)
|
||||
_, err = service.CompleteDirect(context.Background(), user, chat, result.ID)
|
||||
requireDirectError(t, err, sample.status, sample.code)
|
||||
}
|
||||
result, service := beginDirect(t, f, store, objects, user, chat, png, "image/png")
|
||||
wrong := append([]byte(nil), png...)
|
||||
wrong[len(wrong)-1] ^= 1
|
||||
if postDirect(t, result.Upload, wrong, nil) != 204 {
|
||||
t.Fatal("form POST failed")
|
||||
}
|
||||
_, err := service.CompleteDirect(context.Background(), user, chat, result.ID)
|
||||
requireDirectError(t, err, 400, "upload_checksum_mismatch")
|
||||
result, service = beginDirect(t, f, store, objects, user, chat, png, "image/png")
|
||||
if postDirect(t, result.Upload, append(png, 1), nil) < 400 {
|
||||
t.Fatal("S3 did not enforce exact policy size")
|
||||
}
|
||||
u, _ := store.GetDirect(context.Background(), result.ID, chat, user)
|
||||
// Simulate a trusted-side fault that bypassed policy; complete must still check.
|
||||
if err = objects.Put(context.Background(), u.StagingKey, bytes.NewReader(png[:40]), 40, "image/png"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = service.CompleteDirect(context.Background(), user, chat, result.ID)
|
||||
requireDirectError(t, err, 400, "upload_size_mismatch")
|
||||
}
|
||||
|
||||
func TestDirectUploadAccess(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
png := uploadPNG(t)
|
||||
result, service := beginDirect(t, f, store, objects, user, chat, png, "image/png")
|
||||
eve, _ := createTestUser(t, f.users, "eve", "Eve")
|
||||
bob, _ := createTestUser(t, f.users, "bob", "Bob")
|
||||
if _, err := f.db.Exec(context.Background(), `INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)`, chat, bob.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other := createTestChat(t, f.chats, "other", []string{user})
|
||||
router := attachmentRouter(f, objects)
|
||||
path := "/api/v1/chats/" + chat + "/attachment-uploads"
|
||||
for _, actor := range []string{eve.ID, bob.ID} {
|
||||
attachmentCall(t, f, router, "POST", path+"/"+result.ID+"/complete", actor, "", nil, 404)
|
||||
}
|
||||
attachmentCall(t, f, router, "POST", path+"/"+result.ID+"/complete", "", "", nil, 401)
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+other.ID+"/attachment-uploads/"+result.ID+"/complete", user, "", nil, 404)
|
||||
body, _ := json.Marshal(directInput(png, "image/png"))
|
||||
attachmentCall(t, f, router, "POST", path, eve.ID, "application/json", body, 404)
|
||||
u, _ := store.GetDirect(context.Background(), result.ID, chat, user)
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+chat+"/messages", user, "application/json", []byte(`{"text":"","attachment_ids":["`+u.AttachmentID+`"]}`), 404)
|
||||
_, err := service.CompleteDirect(context.Background(), user, chat, result.ID)
|
||||
requireDirectError(t, err, 409, "upload_not_uploaded")
|
||||
for _, change := range []func(map[string]string){
|
||||
func(fields map[string]string) { fields["key"] = "originals/" + uuid.NewString() },
|
||||
func(fields map[string]string) { fields["Content-Type"] = "image/jpeg" },
|
||||
func(fields map[string]string) { fields["x-amz-signature"] = strings.Repeat("0", 64) },
|
||||
} {
|
||||
if postDirect(t, result.Upload, png, change) < 400 {
|
||||
t.Fatal("S3 accepted tampered form")
|
||||
}
|
||||
}
|
||||
expired, err := objects.PresignDirect(context.Background(), u.StagingKey, "image/png", int64(len(png)), time.Now().Add(-time.Minute))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if postDirect(t, expired, png, nil) < 400 {
|
||||
t.Fatal("S3 accepted expired form")
|
||||
}
|
||||
if _, err = f.db.Exec(context.Background(), `UPDATE direct_uploads SET complete_before=clock_timestamp()-interval '1 second' WHERE id=$1`, result.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = service.CompleteDirect(context.Background(), user, chat, result.ID)
|
||||
requireDirectError(t, err, 409, "upload_expired")
|
||||
}
|
||||
|
||||
type directFault struct {
|
||||
*repositories.ObjectStore
|
||||
afterCopy func() error
|
||||
failGet bool
|
||||
}
|
||||
|
||||
func (f directFault) Copy(ctx context.Context, source, dest, etag string) error {
|
||||
if err := f.ObjectStore.Copy(ctx, source, dest, etag); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.afterCopy != nil {
|
||||
return f.afterCopy()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (f directFault) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
if f.failGet {
|
||||
return nil, errors.New("injected GET failure")
|
||||
}
|
||||
return f.ObjectStore.Get(ctx, key)
|
||||
}
|
||||
|
||||
func TestDirectUploadRecoveryConcurrentComplete(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
data := uploadPNG(t)
|
||||
result, _ := beginDirect(t, f, store, objects, user, chat, data, "image/png")
|
||||
if postDirect(t, result.Upload, data, nil) != 204 {
|
||||
t.Fatal("POST failed")
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
ids := make(chan string, 2)
|
||||
errs := make(chan error, 2)
|
||||
for i := 0; i < 2; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
a, err := services.NewAttachmentService(store, objects).CompleteDirect(context.Background(), user, chat, result.ID)
|
||||
ids <- a.ID
|
||||
errs <- err
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(ids)
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
first := <-ids
|
||||
if second := <-ids; first == "" || first != second {
|
||||
t.Fatal("concurrent complete produced different attachments")
|
||||
}
|
||||
var n int
|
||||
if err := f.db.QueryRow(context.Background(), `SELECT count(*) FROM attachments`).Scan(&n); err != nil || n != 1 {
|
||||
t.Fatal("unexpected metadata count", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectUploadRecoveryFailures(t *testing.T) {
|
||||
for _, name := range []string{"copy-result-loss", "get-failure", "metadata-rejection", "database-disconnect"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
data := uploadPNG(t)
|
||||
result, normal := beginDirect(t, f, store, objects, user, chat, data, "image/png")
|
||||
if postDirect(t, result.Upload, data, nil) != 204 {
|
||||
t.Fatal("POST failed")
|
||||
}
|
||||
fault := directFault{ObjectStore: objects}
|
||||
switch name {
|
||||
case "copy-result-loss":
|
||||
fault.afterCopy = func() error { return errors.New("COPY acknowledgement lost") }
|
||||
case "get-failure":
|
||||
fault.failGet = true
|
||||
case "metadata-rejection":
|
||||
if _, err := f.db.Exec(context.Background(), `ALTER TABLE attachments ADD CONSTRAINT reject_direct CHECK (filename <> 'direct.png')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "database-disconnect":
|
||||
fault.afterCopy = func() error {
|
||||
_, err := f.db.Exec(context.Background(), `SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name=$1 AND state='idle in transaction' AND pid<>pg_backend_pid()`, f.db.Config().ConnConfig.RuntimeParams["application_name"])
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err := services.NewAttachmentService(store, fault).CompleteDirect(context.Background(), user, chat, result.ID)
|
||||
if err == nil {
|
||||
t.Fatal("expected injected failure")
|
||||
}
|
||||
var count int
|
||||
if err = f.db.QueryRow(context.Background(), `SELECT count(*) FROM upload_attempts`).Scan(&count); err != nil || count != 1 {
|
||||
t.Fatal("durable journal missing", err)
|
||||
}
|
||||
if err = f.db.QueryRow(context.Background(), `SELECT count(*) FROM attachments`).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatal("published incomplete attachment", err)
|
||||
}
|
||||
if name == "metadata-rejection" {
|
||||
if _, err = f.db.Exec(context.Background(), `ALTER TABLE attachments DROP CONSTRAINT reject_direct`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err = normal.CompleteDirect(context.Background(), user, chat, result.ID); err != nil {
|
||||
t.Fatal("retry failed", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectUploadRecoveryProcessExit(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
data := uploadPNG(t)
|
||||
result, _ := beginDirect(t, f, store, objects, user, chat, data, "image/png")
|
||||
if postDirect(t, result.Upload, data, nil) != 204 {
|
||||
t.Fatal("POST failed")
|
||||
}
|
||||
child := exec.Command(os.Args[0], "-test.run=^TestDirectUploadCrashHelper$")
|
||||
child.Env = append(os.Environ(), "DIRECT_CRASH_HELPER=1", "UPLOAD_TEST_DATABASE="+f.db.Config().ConnString(), "UPLOAD_TEST_SCHEMA="+f.db.Config().ConnConfig.RuntimeParams["search_path"], "UPLOAD_TEST_USER="+user, "UPLOAD_TEST_CHAT="+chat, "DIRECT_UPLOAD_ID="+result.ID)
|
||||
output, err := child.CombinedOutput()
|
||||
var exit *exec.ExitError
|
||||
if !errors.As(err, &exit) || exit.ExitCode() != 23 {
|
||||
t.Fatalf("helper did not crash after COPY: %v %s", err, output)
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
}
|
||||
|
||||
func TestDirectUploadCrashHelper(t *testing.T) {
|
||||
if os.Getenv("DIRECT_CRASH_HELPER") != "1" {
|
||||
return
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(os.Getenv("UPLOAD_TEST_DATABASE"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = os.Getenv("UPLOAD_TEST_SCHEMA")
|
||||
cfg.ConnConfig.RuntimeParams["application_name"] = os.Getenv("UPLOAD_TEST_SCHEMA")
|
||||
db, err := pgxpool.NewWithConfig(context.Background(), cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
objects := uploadObjects(t)
|
||||
fault := directFault{ObjectStore: objects, afterCopy: func() error { os.Exit(23); return nil }}
|
||||
_, err = services.NewAttachmentService(repositories.NewAttachmentStore(db), fault).CompleteDirect(context.Background(), os.Getenv("UPLOAD_TEST_USER"), os.Getenv("UPLOAD_TEST_CHAT"), os.Getenv("DIRECT_UPLOAD_ID"))
|
||||
t.Fatalf("helper failed before exit: %v", err)
|
||||
}
|
||||
|
||||
func TestDirectUploadRecoverySharedSlotAndCancellation(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
data := uploadPNG(t)
|
||||
result, _ := beginDirect(t, f, store, objects, user, chat, data, "image/png")
|
||||
if postDirect(t, result.Upload, data, nil) != 204 {
|
||||
t.Fatal("POST failed")
|
||||
}
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
fault := directFault{ObjectStore: objects, afterCopy: func() error {
|
||||
close(entered)
|
||||
<-release
|
||||
return errors.New("injected operation cancellation")
|
||||
}}
|
||||
service := services.NewAttachmentService(store, fault)
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := service.CompleteDirect(context.Background(), user, chat, result.ID); done <- err }()
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("COPY not reached")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, proxyErr := service.Upload(ctx, user, chat, "waiting.png", "image/png", bytes.NewReader(data))
|
||||
_, directErr := service.CompleteDirect(ctx, user, chat, result.ID)
|
||||
close(release)
|
||||
if err := <-done; err == nil {
|
||||
t.Fatal("injected failure ignored")
|
||||
}
|
||||
if !errors.Is(proxyErr, context.Canceled) || !errors.Is(directErr, context.Canceled) {
|
||||
t.Fatalf("waiting requests ignored cancellation: proxy=%v direct=%v", proxyErr, directErr)
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
}
|
||||
@@ -100,6 +100,13 @@ func newTestFixture(t *testing.T) *testFixture {
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ddl, err = os.ReadFile("../repositories/migrations/000006_direct_uploads.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)
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test:direct-upload": "node --test tests/directUpload.test.cjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "19.3.0",
|
||||
|
||||
+288
-252
@@ -2,291 +2,327 @@ import { useCallback, useEffect, useRef, useState, type FormEvent } from "react"
|
||||
import { api, ApiError, type Attachment, type Chat, type Session, type User } from "./api";
|
||||
|
||||
import AttachmentImage from "./AttachmentImage";
|
||||
import { uploadDirect, type DirectProgress } from "./directUpload";
|
||||
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 : "Неизвестная ошибка";
|
||||
if (error instanceof ApiError) {
|
||||
const uploadMessages: Record<string, string> = {
|
||||
upload_not_uploaded: "Файл ещё не найден в S3. Нажмите «Повторить».",
|
||||
upload_expired: "Срок подтверждения загрузки истёк. Нажмите «Повторить».",
|
||||
upload_size_mismatch: "Размер полученного файла отличается от заявленного.",
|
||||
upload_checksum_mismatch: "Контрольная сумма полученного файла не совпала.",
|
||||
unsupported_media_type: "Файл повреждён или его содержимое не соответствует PNG/JPEG.",
|
||||
payload_too_large: "Изображение превышает 10 МиБ или 40 миллионов пикселей.",
|
||||
};
|
||||
const message = uploadMessages[error.code || ""] || error.message;
|
||||
return error.requestId
|
||||
? `${message} · запрос ${error.requestId}`
|
||||
: message;
|
||||
}
|
||||
return error instanceof Error ? error.message : "Неизвестная ошибка";
|
||||
}
|
||||
|
||||
function authErrorText(error: unknown): string {
|
||||
if (!(error instanceof ApiError)) return errorText(error);
|
||||
const message = error.status === 409
|
||||
? "Имя пользователя уже занято. Выберите другое или войдите."
|
||||
: error.status === 401
|
||||
? "Неверное имя пользователя или пароль."
|
||||
: error.status === 503
|
||||
? "Сервер временно недоступен. Попробуйте ещё раз позже."
|
||||
: error.message;
|
||||
return error.requestId ? `${message} · запрос ${error.requestId}` : message;
|
||||
if (!(error instanceof ApiError)) return errorText(error);
|
||||
const message = error.status === 409
|
||||
? "Имя пользователя уже занято. Выберите другое или войдите."
|
||||
: error.status === 401
|
||||
? "Неверное имя пользователя или пароль."
|
||||
: error.status === 503
|
||||
? "Сервер временно недоступен. Попробуйте ещё раз позже."
|
||||
: error.message;
|
||||
return error.requestId ? `${message} · запрос ${error.requestId}` : message;
|
||||
}
|
||||
|
||||
function dateText(value: string): string {
|
||||
return new Date(value).toLocaleString("ru-RU", {
|
||||
dateStyle: "short",
|
||||
timeStyle: "short",
|
||||
});
|
||||
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("");
|
||||
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)) {
|
||||
setError("Имя пользователя: 3–32 символа, только строчные латинские буквы, цифры и _.");
|
||||
return;
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError("");
|
||||
const name = username.trim();
|
||||
if (!/^[a-z0-9_]{3,32}$/.test(name)) {
|
||||
setError("Имя пользователя: 3–32 символа, только строчные латинские буквы, цифры и _.");
|
||||
return;
|
||||
}
|
||||
const passwordLength = Array.from(password).length;
|
||||
if (passwordLength < 12 || passwordLength > 128 || (mode === "register" && !password.trim())) {
|
||||
setError("Пароль должен содержать от 12 до 128 символов.");
|
||||
return;
|
||||
}
|
||||
if (mode === "register" && (!displayName.trim() || Array.from(displayName.trim()).length > 100)) {
|
||||
setError("Отображаемое имя должно содержать от 1 до 100 символов.");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
let created = false;
|
||||
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) {
|
||||
setError(created
|
||||
? `Аккаунт создан, но войти не удалось. Повторите вход: ${authErrorText(cause)}`
|
||||
: authErrorText(cause));
|
||||
if (created) setMode("login");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
const passwordLength = Array.from(password).length;
|
||||
if (passwordLength < 12 || passwordLength > 128 || (mode === "register" && !password.trim())) {
|
||||
setError("Пароль должен содержать от 12 до 128 символов.");
|
||||
return;
|
||||
}
|
||||
if (mode === "register" && (!displayName.trim() || Array.from(displayName.trim()).length > 100)) {
|
||||
setError("Отображаемое имя должно содержать от 1 до 100 символов.");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
let created = false;
|
||||
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) {
|
||||
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>
|
||||
<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>
|
||||
);
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
type UploadDraft = { localId: string; file: File; status: "uploading" | "ready" | "error"; attachment?: Attachment; error?: string };
|
||||
type UploadDraft = { localId: string; file: File; mode: "proxy" | "direct"; direct: DirectProgress; status: "preparing" | "uploading" | "checking" | "ready" | "error"; attachment?: Attachment; error?: string };
|
||||
|
||||
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, { body: string; key: string }>>({});
|
||||
const [uploads, setUploads] = useState<Record<string, UploadDraft[]>>({});
|
||||
const [uploading, setUploading] = 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);
|
||||
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, { body: string; key: string }>>({});
|
||||
const [uploads, setUploads] = useState<Record<string, UploadDraft[]>>({});
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadMode, setUploadMode] = useState<"proxy" | "direct">("proxy");
|
||||
const uploadController = useRef(new AbortController());
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
uploadController.current = controller;
|
||||
return () => controller.abort();
|
||||
}, []);
|
||||
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 uploadFiles(targetChat: string, items: UploadDraft[]) {
|
||||
setUploading(true); setError("");
|
||||
const update = (id: string, patch: Partial<UploadDraft>) => setUploads(current => ({ ...current,
|
||||
[targetChat]: (current[targetChat] || []).map(item => item.localId === id ? { ...item, ...patch } : item) }));
|
||||
try {
|
||||
for (const item of items) {
|
||||
update(item.localId, { status: "uploading", error: undefined });
|
||||
async function createChat(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!title.trim()) return;
|
||||
setCreating(true); setError("");
|
||||
try {
|
||||
const attachment = await api.uploadAttachment(token, targetChat, item.file);
|
||||
update(item.localId, { status: "ready", attachment });
|
||||
} catch (cause) {
|
||||
update(item.localId, { status: "error", error: errorText(cause) });
|
||||
reportError(cause);
|
||||
if (cause instanceof ApiError && cause.status === 401) break;
|
||||
}
|
||||
}
|
||||
} finally { setUploading(false); }
|
||||
}
|
||||
|
||||
function selectFiles(files: FileList | null) {
|
||||
if (!files || uploading || sending) return;
|
||||
const current = uploads[chatId] || [];
|
||||
const chosen = Array.from(files);
|
||||
if (current.length + chosen.length > 10) { setError("Можно прикрепить не более 10 изображений."); return; }
|
||||
if (chosen.some(file => file.size > 10485760 || !["image/png", "image/jpeg"].includes(file.type))) {
|
||||
setError("Выберите PNG или JPEG размером до 10 МиБ каждый."); return;
|
||||
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); }
|
||||
}
|
||||
const items: UploadDraft[] = chosen.map(file => ({ localId: crypto.randomUUID(), file, status: "uploading" }));
|
||||
setUploads(previous => ({ ...previous, [chatId]: [...current, ...items] }));
|
||||
void uploadFiles(chatId, items);
|
||||
}
|
||||
|
||||
async function sendMessage(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const text = (drafts[chatId] || "").trim();
|
||||
const selected = uploads[chatId] || [];
|
||||
if (uploading || selected.some(item => item.status !== "ready") || (!text && selected.length === 0)) return;
|
||||
const attachmentIds = selected.map(item => item.attachment!.id);
|
||||
const body = JSON.stringify({ text, attachment_ids: attachmentIds });
|
||||
const previous = pendingMessages.current[chatId];
|
||||
const pending = previous?.body === body ? previous : { body, 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, attachmentIds);
|
||||
delete pendingMessages.current[chatId];
|
||||
setDrafts((previous) => ({ ...previous, [chatId]: "" }));
|
||||
setUploads(previous => ({ ...previous, [chatId]: [] }));
|
||||
messages.reload(); setNotice("Сообщение отправлено");
|
||||
} catch (cause) { reportError(cause); }
|
||||
finally { setSending(false); }
|
||||
}
|
||||
async function uploadFiles(targetChat: string, items: UploadDraft[]) {
|
||||
const signal = uploadController.current.signal;
|
||||
setUploading(true); setError("");
|
||||
const update = (id: string, patch: Partial<UploadDraft>) => setUploads(current => ({
|
||||
...current,
|
||||
[targetChat]: (current[targetChat] || []).map(item => item.localId === id ? { ...item, ...patch } : item)
|
||||
}));
|
||||
try {
|
||||
for (const item of items) {
|
||||
if (signal.aborted) break;
|
||||
update(item.localId, { status: "uploading", error: undefined });
|
||||
try {
|
||||
const attachment = item.mode === "direct"
|
||||
? await uploadDirect(token, targetChat, item.file, item.direct, signal, status => { if (!signal.aborted) update(item.localId, { status }); })
|
||||
: await api.uploadAttachment(token, targetChat, item.file, signal);
|
||||
if (signal.aborted) break;
|
||||
update(item.localId, { status: "ready", attachment });
|
||||
} catch (cause) {
|
||||
if (signal.aborted) break;
|
||||
update(item.localId, { status: "error", error: errorText(cause) });
|
||||
reportError(cause);
|
||||
if (cause instanceof ApiError && cause.status === 401) break;
|
||||
}
|
||||
}
|
||||
} finally { if (!signal.aborted) setUploading(false); }
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try { await api.logout(token); onLogout(); }
|
||||
catch (cause) { reportError(cause); }
|
||||
}
|
||||
function selectFiles(files: FileList | null) {
|
||||
if (!files || uploading || sending) return;
|
||||
const current = uploads[chatId] || [];
|
||||
const chosen = Array.from(files);
|
||||
if (current.length + chosen.length > 10) { setError("Можно прикрепить не более 10 изображений."); return; }
|
||||
if (chosen.some(file => file.size < 1 || file.size > 10485760 || !["image/png", "image/jpeg"].includes(file.type))) {
|
||||
setError("Выберите PNG или JPEG размером до 10 МиБ каждый."); return;
|
||||
}
|
||||
const items: UploadDraft[] = chosen.map(file => ({ localId: crypto.randomUUID(), file, mode: uploadMode, direct: {}, status: "preparing" }));
|
||||
setUploads(previous => ({ ...previous, [chatId]: [...current, ...items] }));
|
||||
void uploadFiles(chatId, items);
|
||||
}
|
||||
|
||||
async function copyId() {
|
||||
try { await navigator.clipboard.writeText(user.id); setNotice("ID скопирован"); }
|
||||
catch { setError("Не удалось скопировать ID. Выделите его вручную."); }
|
||||
}
|
||||
async function sendMessage(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const text = (drafts[chatId] || "").trim();
|
||||
const selected = uploads[chatId] || [];
|
||||
if (uploading || selected.some(item => item.status !== "ready") || (!text && selected.length === 0)) return;
|
||||
const attachmentIds = selected.map(item => item.attachment!.id);
|
||||
const body = JSON.stringify({ text, attachment_ids: attachmentIds });
|
||||
const previous = pendingMessages.current[chatId];
|
||||
const pending = previous?.body === body ? previous : { body, 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, attachmentIds);
|
||||
delete pendingMessages.current[chatId];
|
||||
setDrafts((previous) => ({ ...previous, [chatId]: "" }));
|
||||
setUploads(previous => ({ ...previous, [chatId]: [] }));
|
||||
messages.reload(); setNotice("Сообщение отправлено");
|
||||
} catch (cause) { reportError(cause); }
|
||||
finally { setSending(false); }
|
||||
}
|
||||
|
||||
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 || uploading} 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>)}
|
||||
async function logout() {
|
||||
uploadController.current.abort();
|
||||
uploadController.current = new AbortController();
|
||||
setUploading(false);
|
||||
setUploads({});
|
||||
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 || uploading} 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>{message.text && <p>{message.text}</p>}{message.attachment_ids.map(id => <AttachmentImage key={id} id={id} token={token} onError={reportError} />)}</article>)}
|
||||
</div>
|
||||
<Pagination label="Сообщения" page={messages} />
|
||||
<form className="composer" onSubmit={sendMessage}>
|
||||
<div className="composer-fields">
|
||||
<textarea aria-label="Сообщение" value={drafts[chatId] || ""} onChange={(event) => setDrafts({ ...drafts, [chatId]: event.target.value })} disabled={sending} rows={2} maxLength={4000} placeholder="Сообщение…" />
|
||||
<label className="file-picker">Прикрепить PNG или JPEG · до 10 МиБ
|
||||
<input type="file" accept="image/png,image/jpeg" multiple disabled={sending || uploading || (uploads[chatId] || []).length >= 10} onChange={event => { selectFiles(event.target.files); event.target.value = ""; }} />
|
||||
</label>
|
||||
<label className="upload-method">
|
||||
Способ загрузки
|
||||
<select value={uploadMode} disabled={sending || uploading} onChange={event => setUploadMode(event.target.value as "proxy" | "direct")}>
|
||||
<option value="proxy">Через API</option>
|
||||
<option value="direct">Напрямую в S3</option>
|
||||
</select>
|
||||
</label>
|
||||
<ul className="upload-list" aria-live="polite">{(uploads[chatId] || []).map(item => <li key={item.localId}>
|
||||
<span><strong>{item.file.name}</strong> · {(item.file.size / 1048576).toFixed(2)} МиБ<br />
|
||||
{item.mode === "direct" ? "Напрямую в S3 · " : "Через API · "}{item.status === "preparing" ? "Подготовка…" : item.status === "uploading" ? "Загрузка…" : item.status === "checking" ? "Проверка…" : item.status === "ready" ? "Готово к отправке" : item.error}</span>
|
||||
{item.status === "error" && <button type="button" disabled={uploading || sending} onClick={() => void uploadFiles(chatId, [item])}>Повторить</button>}
|
||||
<button type="button" disabled={uploading || sending} aria-label={`Убрать ${item.file.name}`} onClick={() => setUploads(previous => ({ ...previous, [chatId]: (previous[chatId] || []).filter(upload => upload.localId !== item.localId) }))}>Убрать</button>
|
||||
</li>)}</ul>
|
||||
</div>
|
||||
<button className="primary" disabled={sending || uploading || messages.busy || (uploads[chatId] || []).some(item => item.status !== "ready") || (!(drafts[chatId] || "").trim() && !(uploads[chatId] || []).length)}>{sending ? "Отправка…" : uploading ? "Загрузка…" : "Отправить"}</button>
|
||||
</form>
|
||||
</>}
|
||||
</main>
|
||||
</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>{message.text && <p>{message.text}</p>}{message.attachment_ids.map(id => <AttachmentImage key={id} id={id} token={token} onError={reportError} />)}</article>)}
|
||||
</div>
|
||||
<Pagination label="Сообщения" page={messages} />
|
||||
<form className="composer" onSubmit={sendMessage}>
|
||||
<div className="composer-fields">
|
||||
<textarea aria-label="Сообщение" value={drafts[chatId] || ""} onChange={(event) => setDrafts({ ...drafts, [chatId]: event.target.value })} disabled={sending} rows={2} maxLength={4000} placeholder="Сообщение…" />
|
||||
<label className="file-picker">Прикрепить PNG или JPEG · до 10 МиБ
|
||||
<input type="file" accept="image/png,image/jpeg" multiple disabled={sending || uploading || (uploads[chatId] || []).length >= 10} onChange={event => { selectFiles(event.target.files); event.target.value = ""; }} />
|
||||
</label>
|
||||
<ul className="upload-list" aria-live="polite">{(uploads[chatId] || []).map(item => <li key={item.localId}>
|
||||
<span><strong>{item.file.name}</strong> · {(item.file.size / 1048576).toFixed(2)} МиБ<br />
|
||||
{item.status === "uploading" ? "Загрузка…" : item.status === "ready" ? "Готово к отправке" : item.error}</span>
|
||||
{item.status === "error" && <button type="button" disabled={uploading || sending} onClick={() => void uploadFiles(chatId, [item])}>Повторить</button>}
|
||||
<button type="button" disabled={uploading || sending} aria-label={`Убрать ${item.file.name}`} onClick={() => setUploads(previous => ({ ...previous, [chatId]: (previous[chatId] || []).filter(upload => upload.localId !== item.localId) }))}>Убрать</button>
|
||||
</li>)}</ul>
|
||||
</div>
|
||||
<button className="primary" disabled={sending || uploading || messages.busy || (uploads[chatId] || []).some(item => item.status !== "ready") || (!(drafts[chatId] || "").trim() && !(uploads[chatId] || []).length)}>{sending ? "Отправка…" : uploading ? "Загрузка…" : "Отправить"}</button>
|
||||
</form>
|
||||
</>}
|
||||
</main>
|
||||
</div>
|
||||
</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);
|
||||
}, []);
|
||||
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; };
|
||||
}, []);
|
||||
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>}</>;
|
||||
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>}</>;
|
||||
}
|
||||
|
||||
@@ -2,34 +2,34 @@ import { useEffect, useState } from "react";
|
||||
import { api } from "./api";
|
||||
|
||||
export default function AttachmentImage({ id, token, onError }: {
|
||||
id: string; token: string; onError: (error: unknown) => void;
|
||||
id: string; token: string; onError: (error: unknown) => void;
|
||||
}) {
|
||||
const [source, setSource] = useState("");
|
||||
const [filename, setFilename] = useState("Изображение");
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
let objectURL = "";
|
||||
setSource(""); setFailed(false);
|
||||
async function load() {
|
||||
try {
|
||||
const attachment = await api.attachment(token, id, controller.signal);
|
||||
const content = await api.attachmentContent(token, id, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
objectURL = URL.createObjectURL(content);
|
||||
setFilename(attachment.filename); setSource(objectURL);
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) { setFailed(true); onError(error); }
|
||||
}
|
||||
}
|
||||
void load();
|
||||
return () => { controller.abort(); if (objectURL) URL.revokeObjectURL(objectURL); };
|
||||
}, [id, token, attempt, onError]);
|
||||
return <figure className="attachment-image">
|
||||
{source ? <a href={source} download={filename} aria-label={`Скачать ${filename}`}><img src={source} alt={filename} /></a>
|
||||
: failed ? <button type="button" onClick={() => setAttempt(attempt + 1)}>Повторить загрузку изображения</button>
|
||||
: <span role="status">Загрузка изображения…</span>}
|
||||
{source && <figcaption>{filename} · нажмите, чтобы скачать</figcaption>}
|
||||
</figure>;
|
||||
const [source, setSource] = useState("");
|
||||
const [filename, setFilename] = useState("Изображение");
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
let objectURL = "";
|
||||
setSource(""); setFailed(false);
|
||||
async function load() {
|
||||
try {
|
||||
const attachment = await api.attachment(token, id, controller.signal);
|
||||
const content = await api.attachmentContent(token, id, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
objectURL = URL.createObjectURL(content);
|
||||
setFilename(attachment.filename); setSource(objectURL);
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) { setFailed(true); onError(error); }
|
||||
}
|
||||
}
|
||||
void load();
|
||||
return () => { controller.abort(); if (objectURL) URL.revokeObjectURL(objectURL); };
|
||||
}, [id, token, attempt, onError]);
|
||||
return <figure className="attachment-image">
|
||||
{source ? <a href={source} download={filename} aria-label={`Скачать ${filename}`}><img src={source} alt={filename} /></a>
|
||||
: failed ? <button type="button" onClick={() => setAttempt(attempt + 1)}>Повторить загрузку изображения</button>
|
||||
: <span role="status">Загрузка изображения…</span>}
|
||||
{source && <figcaption>{filename} · нажмите, чтобы скачать</figcaption>}
|
||||
</figure>;
|
||||
}
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
interface PaginationProps {
|
||||
label: string;
|
||||
page: {
|
||||
number: number; size: number; range: string; busy: boolean;
|
||||
hasPrevious: boolean; hasNext: boolean;
|
||||
previous: () => void; next: () => void; resize: (size: number) => void;
|
||||
};
|
||||
label: string;
|
||||
page: {
|
||||
number: number; size: number; range: string; busy: boolean;
|
||||
hasPrevious: boolean; hasNext: boolean;
|
||||
previous: () => void; next: () => void; resize: (size: number) => void;
|
||||
};
|
||||
}
|
||||
|
||||
export default function Pagination({ label, page }: PaginationProps) {
|
||||
return <nav className="pagination" aria-label={label}>
|
||||
<div className="page-settings">
|
||||
<label>По <select aria-label={`${label}: размер страницы`} value={page.size} disabled={page.busy} onChange={(event) => page.resize(Number(event.target.value))}>
|
||||
{[2, 5, 10, 25, 50].map((size) => <option key={size} value={size}>{size}</option>)}
|
||||
</select></label>
|
||||
<span className="page-range" aria-live="polite">{page.busy ? "Загрузка…" : `Записи ${page.range}`}</span>
|
||||
</div>
|
||||
<div className="page-navigation">
|
||||
<button type="button" aria-label={`${label}: назад`} onClick={page.previous} disabled={page.busy || !page.hasPrevious}>Назад</button>
|
||||
<span aria-live="polite">Стр. {page.number}</span>
|
||||
<button type="button" aria-label={`${label}: далее`} onClick={page.next} disabled={page.busy || !page.hasNext}>Далее</button>
|
||||
</div>
|
||||
</nav>;
|
||||
return <nav className="pagination" aria-label={label}>
|
||||
<div className="page-settings">
|
||||
<label>По <select aria-label={`${label}: размер страницы`} value={page.size} disabled={page.busy} onChange={(event) => page.resize(Number(event.target.value))}>
|
||||
{[2, 5, 10, 25, 50].map((size) => <option key={size} value={size}>{size}</option>)}
|
||||
</select></label>
|
||||
<span className="page-range" aria-live="polite">{page.busy ? "Загрузка…" : `Записи ${page.range}`}</span>
|
||||
</div>
|
||||
<div className="page-navigation">
|
||||
<button type="button" aria-label={`${label}: назад`} onClick={page.previous} disabled={page.busy || !page.hasPrevious}>Назад</button>
|
||||
<span aria-live="polite">Стр. {page.number}</span>
|
||||
<button type="button" aria-label={`${label}: далее`} onClick={page.next} disabled={page.busy || !page.hasNext}>Далее</button>
|
||||
</div>
|
||||
</nav>;
|
||||
}
|
||||
|
||||
+130
-111
@@ -1,148 +1,167 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
created_at: string;
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Chat {
|
||||
id: string;
|
||||
title: string;
|
||||
member_ids: string[];
|
||||
created_at: string;
|
||||
id: string;
|
||||
title: string;
|
||||
member_ids: string[];
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Attachment {
|
||||
id: string; chat_id: string; owner_id: string; filename: string;
|
||||
content_type: "image/png" | "image/jpeg"; size_bytes: number; sha256: string;
|
||||
status: "ready"; variants: unknown[]; error_code: null; created_at: string; updated_at: string;
|
||||
id: string; chat_id: string; owner_id: string; filename: string;
|
||||
content_type: "image/png" | "image/jpeg"; size_bytes: number; sha256: string;
|
||||
status: "ready"; variants: unknown[]; error_code: null; created_at: string; updated_at: string;
|
||||
}
|
||||
|
||||
export interface DirectUpload {
|
||||
upload_id: string;
|
||||
expires_at: string;
|
||||
complete_before: string;
|
||||
upload: { method: "POST"; url: string; fields: Record<string, string> };
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
attachment_ids: string[];
|
||||
created_at: string;
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
attachment_ids: string[];
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Page<T> {
|
||||
items: T[];
|
||||
next_cursor: string | null;
|
||||
items: T[];
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
token: string;
|
||||
token_type: string;
|
||||
expires_at: string;
|
||||
user: User;
|
||||
token: string;
|
||||
token_type: string;
|
||||
expires_at: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number,
|
||||
public readonly requestId?: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number,
|
||||
public readonly requestId?: string,
|
||||
public readonly code?: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(path, init);
|
||||
} catch {
|
||||
throw new Error("Не удалось связаться с сервером.");
|
||||
}
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(path, init);
|
||||
} catch (cause) {
|
||||
if (init.signal?.aborted) throw cause;
|
||||
throw new Error("Не удалось связаться с сервером.");
|
||||
}
|
||||
|
||||
if (response.status === 204) return undefined as T;
|
||||
if (response.status === 204) return undefined as T;
|
||||
|
||||
const data: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const error = data as { error?: { message?: string; request_id?: string } } | null;
|
||||
throw new ApiError(
|
||||
error?.error?.message || `Ошибка HTTP ${response.status}`,
|
||||
response.status,
|
||||
error?.error?.request_id,
|
||||
);
|
||||
}
|
||||
return data as T;
|
||||
const data: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const error = data as { error?: { message?: string; request_id?: string; code?: string } } | null;
|
||||
throw new ApiError(
|
||||
error?.error?.message || `Ошибка HTTP ${response.status}`,
|
||||
response.status,
|
||||
error?.error?.request_id,
|
||||
error?.error?.code,
|
||||
);
|
||||
}
|
||||
return data as T;
|
||||
}
|
||||
|
||||
function jsonBody(value: unknown): Pick<RequestInit, "body" | "headers"> {
|
||||
return {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(value),
|
||||
};
|
||||
return {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(value),
|
||||
};
|
||||
}
|
||||
|
||||
function bearer(token: string): HeadersInit {
|
||||
return { Authorization: `Bearer ${token}` };
|
||||
return { Authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
function basic(username: string, password: string): string {
|
||||
const bytes = new TextEncoder().encode(`${username}:${password}`);
|
||||
return `Basic ${btoa(String.fromCharCode(...bytes))}`;
|
||||
const bytes = new TextEncoder().encode(`${username}:${password}`);
|
||||
return `Basic ${btoa(String.fromCharCode(...bytes))}`;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
register: (username: string, displayName: string, password: string) =>
|
||||
request<User>("/api/v1/users", {
|
||||
method: "POST",
|
||||
...jsonBody({ username, display_name: displayName, password }),
|
||||
}),
|
||||
login: (username: string, password: string) =>
|
||||
request<Session>("/api/v1/auth/sessions", {
|
||||
method: "POST",
|
||||
headers: { Authorization: basic(username, password) },
|
||||
}),
|
||||
logout: (token: string) =>
|
||||
request<void>("/api/v1/auth/sessions/current", {
|
||||
method: "DELETE",
|
||||
headers: bearer(token),
|
||||
}),
|
||||
me: (token: string) =>
|
||||
request<User>("/api/v1/users/me", { headers: bearer(token) }),
|
||||
chats: (token: string, cursor?: string, limit = 10) => {
|
||||
const query = new URLSearchParams({ limit: String(limit) });
|
||||
if (cursor) query.set("cursor", cursor);
|
||||
return request<Page<Chat>>(`/api/v1/chats?${query}`, {
|
||||
headers: bearer(token),
|
||||
});
|
||||
},
|
||||
createChat: (token: string, title: string, memberIds: string[]) =>
|
||||
request<Chat>("/api/v1/chats", {
|
||||
method: "POST",
|
||||
headers: { ...bearer(token), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ title, member_ids: memberIds }),
|
||||
}),
|
||||
messages: (token: string, chatId: string, cursor?: string, limit = 10) => {
|
||||
const query = new URLSearchParams({ limit: String(limit) });
|
||||
if (cursor) query.set("cursor", cursor);
|
||||
return request<Page<Message>>(`/api/v1/chats/${encodeURIComponent(chatId)}/messages?${query}`, {
|
||||
headers: bearer(token),
|
||||
});
|
||||
},
|
||||
uploadAttachment: (token: string, chatId: string, file: File) =>
|
||||
request<Attachment>(`/api/v1/chats/${encodeURIComponent(chatId)}/attachments?${new URLSearchParams({ filename: file.name })}`, {
|
||||
method: "POST", headers: { ...bearer(token), "Content-Type": file.type }, body: file,
|
||||
}),
|
||||
attachment: (token: string, id: string, signal?: AbortSignal) =>
|
||||
request<Attachment>(`/api/v1/attachments/${encodeURIComponent(id)}`, { headers: bearer(token), signal }),
|
||||
attachmentContent: async (token: string, id: string, signal?: AbortSignal) => {
|
||||
const response = await fetch(`/api/v1/attachments/${encodeURIComponent(id)}/content`, { headers: bearer(token), signal });
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new ApiError(data?.error?.message || `Ошибка HTTP ${response.status}`, response.status, response.headers.get("X-Request-Id") || undefined);
|
||||
}
|
||||
return response.blob();
|
||||
},
|
||||
sendMessage: (token: string, chatId: string, text: string, idempotencyKey: string, attachmentIds: string[] = []) =>
|
||||
request<Message>(`/api/v1/chats/${encodeURIComponent(chatId)}/messages`, {
|
||||
method: "POST",
|
||||
headers: { ...bearer(token), "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
|
||||
body: JSON.stringify({ text, attachment_ids: attachmentIds }),
|
||||
}),
|
||||
register: (username: string, displayName: string, password: string) =>
|
||||
request<User>("/api/v1/users", {
|
||||
method: "POST",
|
||||
...jsonBody({ username, display_name: displayName, password }),
|
||||
}),
|
||||
login: (username: string, password: string) =>
|
||||
request<Session>("/api/v1/auth/sessions", {
|
||||
method: "POST",
|
||||
headers: { Authorization: basic(username, password) },
|
||||
}),
|
||||
logout: (token: string) =>
|
||||
request<void>("/api/v1/auth/sessions/current", {
|
||||
method: "DELETE",
|
||||
headers: bearer(token),
|
||||
}),
|
||||
me: (token: string) =>
|
||||
request<User>("/api/v1/users/me", { headers: bearer(token) }),
|
||||
chats: (token: string, cursor?: string, limit = 10) => {
|
||||
const query = new URLSearchParams({ limit: String(limit) });
|
||||
if (cursor) query.set("cursor", cursor);
|
||||
return request<Page<Chat>>(`/api/v1/chats?${query}`, {
|
||||
headers: bearer(token),
|
||||
});
|
||||
},
|
||||
createChat: (token: string, title: string, memberIds: string[]) =>
|
||||
request<Chat>("/api/v1/chats", {
|
||||
method: "POST",
|
||||
headers: { ...bearer(token), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ title, member_ids: memberIds }),
|
||||
}),
|
||||
messages: (token: string, chatId: string, cursor?: string, limit = 10) => {
|
||||
const query = new URLSearchParams({ limit: String(limit) });
|
||||
if (cursor) query.set("cursor", cursor);
|
||||
return request<Page<Message>>(`/api/v1/chats/${encodeURIComponent(chatId)}/messages?${query}`, {
|
||||
headers: bearer(token),
|
||||
});
|
||||
},
|
||||
uploadAttachment: (token: string, chatId: string, file: File, signal?: AbortSignal) =>
|
||||
request<Attachment>(`/api/v1/chats/${encodeURIComponent(chatId)}/attachments?${new URLSearchParams({ filename: file.name })}`, {
|
||||
method: "POST", headers: { ...bearer(token), "Content-Type": file.type }, body: file, signal,
|
||||
}),
|
||||
initDirectUpload: (token: string, chatId: string, file: File, sha256: string, signal?: AbortSignal) =>
|
||||
request<DirectUpload>(`/api/v1/chats/${encodeURIComponent(chatId)}/attachment-uploads`, {
|
||||
method: "POST", headers: { ...bearer(token), "Content-Type": "application/json" }, signal,
|
||||
body: JSON.stringify({ filename: file.name, content_type: file.type, size_bytes: file.size, sha256 }),
|
||||
}),
|
||||
completeDirectUpload: (token: string, chatId: string, id: string, signal?: AbortSignal) =>
|
||||
request<Attachment>(`/api/v1/chats/${encodeURIComponent(chatId)}/attachment-uploads/${encodeURIComponent(id)}/complete`, {
|
||||
method: "POST", headers: bearer(token), signal,
|
||||
}),
|
||||
attachment: (token: string, id: string, signal?: AbortSignal) =>
|
||||
request<Attachment>(`/api/v1/attachments/${encodeURIComponent(id)}`, { headers: bearer(token), signal }),
|
||||
attachmentContent: async (token: string, id: string, signal?: AbortSignal) => {
|
||||
const response = await fetch(`/api/v1/attachments/${encodeURIComponent(id)}/content`, { headers: bearer(token), signal });
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new ApiError(data?.error?.message || `Ошибка HTTP ${response.status}`, response.status, response.headers.get("X-Request-Id") || undefined);
|
||||
}
|
||||
return response.blob();
|
||||
},
|
||||
sendMessage: (token: string, chatId: string, text: string, idempotencyKey: string, attachmentIds: string[] = []) =>
|
||||
request<Message>(`/api/v1/chats/${encodeURIComponent(chatId)}/messages`, {
|
||||
method: "POST",
|
||||
headers: { ...bearer(token), "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
|
||||
body: JSON.stringify({ text, attachment_ids: attachmentIds }),
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { api, ApiError, type Attachment, type DirectUpload } from "./api";
|
||||
|
||||
export type UploadStage = "preparing" | "uploading" | "checking";
|
||||
export type DirectProgress = { session?: DirectUpload; sha256?: string; confirmOnly?: boolean };
|
||||
|
||||
async function complete(token: string, chat: string, progress: DirectProgress, signal: AbortSignal): Promise<Attachment> {
|
||||
try {
|
||||
return await api.completeDirectUpload(token, chat, progress.session!.upload_id, signal);
|
||||
} catch (cause) {
|
||||
if (cause instanceof ApiError && [400, 413, 415].includes(cause.status)) {
|
||||
progress.session = undefined;
|
||||
progress.confirmOnly = false;
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
|
||||
export async function uploadDirect(
|
||||
token: string, chat: string, file: File, progress: DirectProgress,
|
||||
signal: AbortSignal, stage: (value: UploadStage) => void,
|
||||
): Promise<Attachment> {
|
||||
if (progress.session) {
|
||||
stage("checking");
|
||||
try { return await complete(token, chat, progress, signal); }
|
||||
catch (cause) {
|
||||
if (!(cause instanceof ApiError)) throw cause;
|
||||
if (cause.code === "upload_expired") {
|
||||
progress.session = undefined; progress.confirmOnly = false;
|
||||
} else if (cause.code === "upload_not_uploaded" && !progress.confirmOnly) {
|
||||
if (Date.now() >= Date.parse(progress.session!.expires_at)) progress.session = undefined;
|
||||
} else throw cause;
|
||||
}
|
||||
}
|
||||
if (!progress.session) {
|
||||
stage("preparing");
|
||||
if (!progress.sha256) {
|
||||
const hash = await crypto.subtle.digest("SHA-256", await file.arrayBuffer());
|
||||
progress.sha256 = Array.from(new Uint8Array(hash), byte => byte.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
progress.session = await api.initDirectUpload(token, chat, file, progress.sha256, signal);
|
||||
progress.confirmOnly = false;
|
||||
}
|
||||
stage("uploading");
|
||||
const form = new FormData();
|
||||
for (const [key, value] of Object.entries(progress.session.upload.fields)) form.append(key, value);
|
||||
form.append("file", file);
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(progress.session.upload.url, { method: "POST", body: form, credentials: "omit", signal });
|
||||
} catch (cause) {
|
||||
if (signal.aborted) throw cause;
|
||||
throw new Error("Не удалось подтвердить передачу в S3. Нажмите «Повторить»: сначала проверим, получен ли файл.");
|
||||
}
|
||||
if (!response.ok) {
|
||||
const xml = new DOMParser().parseFromString(await response.text(), "application/xml");
|
||||
const code = xml.querySelector("Code")?.textContent;
|
||||
const message = code === "EntityTooLarge" || code === "EntityTooSmall"
|
||||
? "S3 отклонил размер файла."
|
||||
: response.status === 403
|
||||
? "S3 отклонил подпись или её срок действия. Нажмите «Повторить»."
|
||||
: "Хранилище временно недоступно. Нажмите «Повторить».";
|
||||
throw new Error(message);
|
||||
}
|
||||
progress.confirmOnly = true;
|
||||
stage("checking");
|
||||
return complete(token, chat, progress, signal);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import App from "./App";
|
||||
import "./styles.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
|
||||
+839
-110
@@ -1,115 +1,844 @@
|
||||
@import url("https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap");
|
||||
|
||||
:root {
|
||||
font-family: "Manrope", "Segoe UI", sans-serif;
|
||||
color: #242925;
|
||||
background: #eef0ed;
|
||||
font-synthesis: none;
|
||||
--accent: #25634b;
|
||||
--muted: #697169;
|
||||
--line: #e4e8e1;
|
||||
font-family: "Manrope", "Segoe UI", sans-serif;
|
||||
color: #242925;
|
||||
background: #eef0ed;
|
||||
font-synthesis: none;
|
||||
--accent: #25634b;
|
||||
--muted: #697169;
|
||||
--line: #e4e8e1;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; }
|
||||
button, input, textarea, select { font: inherit; }
|
||||
button, summary, select { cursor: pointer; }
|
||||
button { border: 1px solid var(--line); border-radius: 8px; background: white; padding: 9px 14px; color: inherit; font-size: 13px; font-weight: 650; transition: background .15s ease, color .15s ease; }
|
||||
button:hover:not(:disabled) { background: #f0f3ee; }
|
||||
button:disabled { cursor: default; color: #879084; background: #f5f6f3; }
|
||||
button:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-visible, summary:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
||||
::selection { background: #d2e6d8; }
|
||||
* { scrollbar-width: thin; scrollbar-color: #c4cec3 transparent; }
|
||||
input, textarea { caret-color: var(--accent); }
|
||||
h1, h2, p { margin: 0; }
|
||||
h1 { font-size: 24px; letter-spacing: -.035em; font-weight: 800; }
|
||||
h2 { font-size: 18px; letter-spacing: -.025em; }
|
||||
.primary { background: var(--accent); border-color: transparent; color: white; }
|
||||
.primary:hover:not(:disabled) { background: #194c38; }
|
||||
.primary:disabled { background: #e0e6de; border-color: transparent; }
|
||||
.quiet { border-color: transparent; background: transparent; color: var(--muted); padding: 7px 9px; }
|
||||
.compact { font-size: 12px; padding: 9px 12px; }
|
||||
.stack { display: grid; gap: 18px; }
|
||||
label { display: grid; gap: 7px; font-size: 12px; font-weight: 700; }
|
||||
input, textarea { width: 100%; min-width: 0; padding: 12px; border: 1px solid #d6ded3; border-radius: 8px; background: #fff; color: inherit; font-size: 14px; font-weight: 400; }
|
||||
input::placeholder, textarea::placeholder { color: #71796f; }
|
||||
textarea { resize: vertical; }
|
||||
.error { color: #a32f33; font-size: 13px; overflow-wrap: anywhere; }
|
||||
.auth-page, .loading-page { min-height: 100dvh; display: grid; place-items: center; padding: 24px; }
|
||||
.auth-card { width: min(100%, 390px); }
|
||||
.auth-card h1 { font-size: 32px; margin: 20px 0 28px; }
|
||||
.brand-mark { width: 48px; height: 48px; border-radius: 14px; background: var(--accent); display: grid; place-items: center; }
|
||||
.brand-mark svg { width: 28px; stroke: white; stroke-width: 1.5; stroke-linejoin: round; fill: none; }
|
||||
.tabs { display: flex; gap: 4px; padding: 4px; border-radius: 10px; background: #e1e7de; margin-bottom: 28px; }
|
||||
.tabs button { flex: 1; border: 0; background: transparent; color: #596554; }
|
||||
.tabs button.active { background: white; color: #242925; }
|
||||
.auth-card .primary { padding: 13px; margin-top: 6px; }
|
||||
.app-shell { width: min(1440px, 100%); height: calc(100dvh - 48px); min-height: 580px; margin: 24px auto; display: flex; flex-direction: column; background: white; border: 1px solid var(--line); border-radius: 16px; overflow: hidden; }
|
||||
.app-header { min-height: 84px; padding: 18px 28px; display: flex; align-items: center; justify-content: space-between; gap: 20px; border-bottom: 1px solid var(--line); }
|
||||
.brand { color: inherit; text-decoration: none; font-size: 21px; font-weight: 800; letter-spacing: -.035em; display: flex; align-items: center; gap: 8px; }
|
||||
.brand-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); }
|
||||
.account { display: flex; gap: 12px; align-items: center; font-size: 13px; }
|
||||
.account strong, .account small { display: block; }
|
||||
.account small { color: var(--muted); font-size: 11px; margin-top: 2px; }
|
||||
.avatar, .chat-avatar { display: grid; place-items: center; flex-shrink: 0; background: #e7eee3; color: #435d3b; border-radius: 12px; width: 38px; height: 38px; font-size: 14px; font-weight: 700; }
|
||||
.banner { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 8px 24px; background: #edf5ee; color: #295735; font-size: 12px; }
|
||||
.banner.error { background: #fff0ee; color: #a32f33; }
|
||||
.banner .quiet { color: inherit; }
|
||||
.toast { position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%); background: #242925; color: white; padding: 12px 18px; border-radius: 10px; font-size: 13px; }
|
||||
.app-content { display: grid; grid-template-columns: 320px minmax(0, 1fr); flex: 1; min-height: 0; }
|
||||
.sidebar { min-height: 0; display: flex; flex-direction: column; border-right: 1px solid var(--line); }
|
||||
.sidebar-heading { padding: 26px 22px 20px; display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.sidebar-heading h1 { font-size: 23px; }
|
||||
.create-form { margin: 0 20px 16px; padding-bottom: 20px; border-bottom: 1px solid var(--line); gap: 12px; overflow-y: auto; flex-shrink: 0; max-height: 38vh; }
|
||||
.list-toolbar { padding: 0 16px 12px 24px; display: flex; justify-content: space-between; align-items: center; color: var(--muted); font-size: 11px; }
|
||||
.chat-list { padding: 0 12px 16px; flex: 1; min-height: 60px; overflow-y: auto; }
|
||||
.chat-item { display: flex; align-items: center; gap: 12px; text-align: left; width: 100%; padding: 14px 12px; border: 0; background: transparent; margin-bottom: 4px; border-radius: 10px; }
|
||||
.chat-item.selected { background: #edf3e9; }
|
||||
.chat-item.selected .chat-avatar { background: #dce8d4; color: #315c27; }
|
||||
.chat-copy { min-width: 0; display: grid; gap: 5px; }
|
||||
.chat-copy strong { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.chat-copy small { font-size: 11px; font-weight: 400; color: var(--muted); }
|
||||
.identity { border-top: 1px solid var(--line); padding: 14px 24px; font-size: 12px; color: var(--muted); }
|
||||
.identity code { display: block; font-size: 10px; margin-top: 12px; overflow-wrap: anywhere; user-select: all; }
|
||||
.identity .quiet { padding-left: 0; }
|
||||
.conversation { min-height: 0; min-width: 0; display: flex; flex-direction: column; background: #fafbf8; }
|
||||
.conversation-empty { display: grid; justify-items: center; gap: 20px; margin: auto; color: var(--muted); padding: 40px; }
|
||||
.conversation-empty svg { width: 48px; stroke: #95a38c; stroke-width: 1.5; fill: none; stroke-linejoin: round; }
|
||||
.conversation-empty h2 { font-size: 16px; font-weight: 500; }
|
||||
.conversation-header { background: white; padding: 24px 28px; display: flex; justify-content: space-between; align-items: start; gap: 16px; border-bottom: 1px solid var(--line); }
|
||||
.conversation-header h2 { overflow-wrap: anywhere; }
|
||||
.members { margin-top: 5px; color: var(--muted); font-size: 11px; }
|
||||
.members code { display: block; overflow-wrap: anywhere; margin-top: 8px; font-size: 10px; }
|
||||
.messages { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; align-items: flex-start; gap: 16px; padding: 28px; }
|
||||
.message { max-width: min(85%, 620px); border-radius: 12px 12px 12px 3px; background: #eaece7; padding: 12px 16px; }
|
||||
.message.own { align-self: flex-end; background: #e2edda; border-radius: 12px 12px 3px 12px; }
|
||||
.message-meta { display: flex; gap: 24px; justify-content: space-between; align-items: baseline; color: #596453; font-size: 10px; font-variant-numeric: tabular-nums; }
|
||||
.message p { margin-top: 7px; line-height: 1.6; font-size: 14px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.empty-note { margin: auto; padding: 24px; text-align: center; color: var(--muted); font-size: 13px; }
|
||||
.pagination { flex-shrink: 0; border-top: 1px solid var(--line); padding: 14px 22px; background: white; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px 24px; font-size: 11px; font-variant-numeric: tabular-nums; }
|
||||
.page-settings, .page-navigation { display: flex; align-items: center; gap: 12px; }
|
||||
.page-settings label { display: flex; align-items: center; gap: 6px; color: var(--muted); font-weight: 500; font-size: 11px; }
|
||||
.page-settings select { border: 1px solid var(--line); background: #fafbf8; border-radius: 6px; padding: 5px; color: inherit; }
|
||||
.page-range { color: var(--muted); }
|
||||
.page-navigation button { padding: 6px 10px; font-size: 11px; }
|
||||
.page-navigation span { min-width: 44px; text-align: center; }
|
||||
.sidebar .page-navigation { width: 100%; justify-content: space-between; }
|
||||
.sidebar .page-settings { width: 100%; justify-content: space-between; }
|
||||
.composer { display: flex; align-items: end; gap: 12px; padding: 20px 28px; background: white; border-top: 1px solid var(--line); }
|
||||
.composer textarea { background: #f7f8f5; border-color: transparent; resize: vertical; max-height: 180px; }
|
||||
.composer .primary { padding: 13px 20px; }
|
||||
@media (max-width: 1488px) { .app-shell { width: calc(100% - 48px); } }
|
||||
@media (max-width: 900px) { .app-shell { width: 100%; height: 100dvh; margin: 0; border: 0; border-radius: 0; } .app-content { grid-template-columns: 280px minmax(0, 1fr); } .messages, .conversation-header { padding: 20px; } .message { max-width: 95%; } .message-meta { gap: 12px; flex-wrap: wrap; } .composer { padding: 16px; } }
|
||||
@media (max-width: 620px) { .app-shell { height: auto; min-height: 100dvh; } .app-header { padding: 18px; } .brand { font-size: 18px; } .account .avatar, .account small { display: none; } .account { gap: 4px; } .app-content { display: flex; flex-direction: column; } .sidebar { border-right: 0; border-bottom: 1px solid var(--line); } .sidebar-heading { padding: 20px; } .chat-list { max-height: 240px; } .sidebar .pagination { flex-wrap: nowrap; } .sidebar .page-settings, .sidebar .page-navigation { width: auto; } .sidebar .page-range { display: none; } .conversation { min-height: 480px; } .messages { max-height: 55dvh; min-height: 180px; } .pagination { padding: 12px 16px; } .composer { gap: 8px; } .composer .primary { padding: 12px; } }
|
||||
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
|
||||
|
||||
.composer-fields { flex: 1; min-width: 0; }
|
||||
.composer-fields textarea { width: 100%; }
|
||||
.file-picker { display: block; margin-top: 10px; color: var(--muted); font-size: 12px; }
|
||||
.file-picker input { display: block; max-width: 100%; margin-top: 6px; }
|
||||
.upload-list { list-style: none; margin: 8px 0 0; padding: 0; }
|
||||
.upload-list li { display: flex; align-items: center; gap: 8px; padding: 8px 0; border-bottom: 1px solid var(--line); font-size: 12px; }
|
||||
.upload-list li span { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
||||
.attachment-image { margin: 10px 0 0; max-width: 100%; }
|
||||
.attachment-image img { display: block; max-width: 100%; max-height: 320px; object-fit: contain; border-radius: 8px; }
|
||||
.attachment-image figcaption { margin-top: 6px; overflow-wrap: anywhere; color: var(--muted); font-size: 12px; }
|
||||
@media (max-width: 600px) { .composer { flex-wrap: wrap; } .composer-fields { flex-basis: 100%; } .upload-list li { flex-wrap: wrap; } }
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
textarea,
|
||||
select {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
button,
|
||||
summary,
|
||||
select {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
background: white;
|
||||
padding: 9px 14px;
|
||||
color: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
transition: background .15s ease, color .15s ease;
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) {
|
||||
background: #f0f3ee;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
cursor: default;
|
||||
color: #879084;
|
||||
background: #f5f6f3;
|
||||
}
|
||||
|
||||
button:focus-visible,
|
||||
input:focus-visible,
|
||||
textarea:focus-visible,
|
||||
select:focus-visible,
|
||||
summary:focus-visible,
|
||||
a:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: #d2e6d8;
|
||||
}
|
||||
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #c4cec3 transparent;
|
||||
}
|
||||
|
||||
input,
|
||||
textarea {
|
||||
caret-color: var(--accent);
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 24px;
|
||||
letter-spacing: -.035em;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 18px;
|
||||
letter-spacing: -.025em;
|
||||
}
|
||||
|
||||
.primary {
|
||||
background: var(--accent);
|
||||
border-color: transparent;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.primary:hover:not(:disabled) {
|
||||
background: #194c38;
|
||||
}
|
||||
|
||||
.primary:disabled {
|
||||
background: #e0e6de;
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
.quiet {
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
padding: 7px 9px;
|
||||
}
|
||||
|
||||
.compact {
|
||||
font-size: 12px;
|
||||
padding: 9px 12px;
|
||||
}
|
||||
|
||||
.stack {
|
||||
display: grid;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
label {
|
||||
display: grid;
|
||||
gap: 7px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
input,
|
||||
textarea {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 12px;
|
||||
border: 1px solid #d6ded3;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
color: inherit;
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
input::placeholder,
|
||||
textarea::placeholder {
|
||||
color: #71796f;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #a32f33;
|
||||
font-size: 13px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.auth-page,
|
||||
.loading-page {
|
||||
min-height: 100dvh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
width: min(100%, 390px);
|
||||
}
|
||||
|
||||
.auth-card h1 {
|
||||
font-size: 32px;
|
||||
margin: 20px 0 28px;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 14px;
|
||||
background: var(--accent);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.brand-mark svg {
|
||||
width: 28px;
|
||||
stroke: white;
|
||||
stroke-width: 1.5;
|
||||
stroke-linejoin: round;
|
||||
fill: none;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 4px;
|
||||
border-radius: 10px;
|
||||
background: #e1e7de;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.tabs button {
|
||||
flex: 1;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #596554;
|
||||
}
|
||||
|
||||
.tabs button.active {
|
||||
background: white;
|
||||
color: #242925;
|
||||
}
|
||||
|
||||
.auth-card .primary {
|
||||
padding: 13px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
width: min(1440px, 100%);
|
||||
height: calc(100dvh - 48px);
|
||||
min-height: 580px;
|
||||
margin: 24px auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: white;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.app-header {
|
||||
min-height: 84px;
|
||||
padding: 18px 28px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 20px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.brand {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
font-size: 21px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -.035em;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.brand-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.account {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.account strong,
|
||||
.account small {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.account small {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.avatar,
|
||||
.chat-avatar {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex-shrink: 0;
|
||||
background: #e7eee3;
|
||||
color: #435d3b;
|
||||
border-radius: 12px;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 8px 24px;
|
||||
background: #edf5ee;
|
||||
color: #295735;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.banner.error {
|
||||
background: #fff0ee;
|
||||
color: #a32f33;
|
||||
}
|
||||
|
||||
.banner .quiet {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.toast {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: #242925;
|
||||
color: white;
|
||||
padding: 12px 18px;
|
||||
border-radius: 10px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.app-content {
|
||||
display: grid;
|
||||
grid-template-columns: 320px minmax(0, 1fr);
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-right: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.sidebar-heading {
|
||||
padding: 26px 22px 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.sidebar-heading h1 {
|
||||
font-size: 23px;
|
||||
}
|
||||
|
||||
.create-form {
|
||||
margin: 0 20px 16px;
|
||||
padding-bottom: 20px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
gap: 12px;
|
||||
overflow-y: auto;
|
||||
flex-shrink: 0;
|
||||
max-height: 38vh;
|
||||
}
|
||||
|
||||
.list-toolbar {
|
||||
padding: 0 16px 12px 24px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.chat-list {
|
||||
padding: 0 12px 16px;
|
||||
flex: 1;
|
||||
min-height: 60px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.chat-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
text-align: left;
|
||||
width: 100%;
|
||||
padding: 14px 12px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
margin-bottom: 4px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.chat-item.selected {
|
||||
background: #edf3e9;
|
||||
}
|
||||
|
||||
.chat-item.selected .chat-avatar {
|
||||
background: #dce8d4;
|
||||
color: #315c27;
|
||||
}
|
||||
|
||||
.chat-copy {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.chat-copy strong {
|
||||
font-size: 13px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chat-copy small {
|
||||
font-size: 11px;
|
||||
font-weight: 400;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.identity {
|
||||
border-top: 1px solid var(--line);
|
||||
padding: 14px 24px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.identity code {
|
||||
display: block;
|
||||
font-size: 10px;
|
||||
margin-top: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
user-select: all;
|
||||
}
|
||||
|
||||
.identity .quiet {
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
.conversation {
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #fafbf8;
|
||||
}
|
||||
|
||||
.conversation-empty {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: 20px;
|
||||
margin: auto;
|
||||
color: var(--muted);
|
||||
padding: 40px;
|
||||
}
|
||||
|
||||
.conversation-empty svg {
|
||||
width: 48px;
|
||||
stroke: #95a38c;
|
||||
stroke-width: 1.5;
|
||||
fill: none;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
|
||||
.conversation-empty h2 {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.conversation-header {
|
||||
background: white;
|
||||
padding: 24px 28px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: start;
|
||||
gap: 16px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.conversation-header h2 {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.members {
|
||||
margin-top: 5px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.members code {
|
||||
display: block;
|
||||
overflow-wrap: anywhere;
|
||||
margin-top: 8px;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.messages {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
padding: 28px;
|
||||
}
|
||||
|
||||
.message {
|
||||
max-width: min(85%, 620px);
|
||||
border-radius: 12px 12px 12px 3px;
|
||||
background: #eaece7;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.message.own {
|
||||
align-self: flex-end;
|
||||
background: #e2edda;
|
||||
border-radius: 12px 12px 3px 12px;
|
||||
}
|
||||
|
||||
.message-meta {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
justify-content: space-between;
|
||||
align-items: baseline;
|
||||
color: #596453;
|
||||
font-size: 10px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.message p {
|
||||
margin-top: 7px;
|
||||
line-height: 1.6;
|
||||
font-size: 14px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.empty-note {
|
||||
margin: auto;
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.pagination {
|
||||
flex-shrink: 0;
|
||||
border-top: 1px solid var(--line);
|
||||
padding: 14px 22px;
|
||||
background: white;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px 24px;
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.page-settings,
|
||||
.page-navigation {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.page-settings label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--muted);
|
||||
font-weight: 500;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.page-settings select {
|
||||
border: 1px solid var(--line);
|
||||
background: #fafbf8;
|
||||
border-radius: 6px;
|
||||
padding: 5px;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.page-range {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.page-navigation button {
|
||||
padding: 6px 10px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.page-navigation span {
|
||||
min-width: 44px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.sidebar .page-navigation {
|
||||
width: 100%;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.sidebar .page-settings {
|
||||
width: 100%;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.composer {
|
||||
display: flex;
|
||||
align-items: end;
|
||||
gap: 12px;
|
||||
padding: 20px 28px;
|
||||
background: white;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.composer textarea {
|
||||
background: #f7f8f5;
|
||||
border-color: transparent;
|
||||
resize: vertical;
|
||||
max-height: 180px;
|
||||
}
|
||||
|
||||
.composer .primary {
|
||||
padding: 13px 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 1488px) {
|
||||
.app-shell {
|
||||
width: calc(100% - 48px);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.app-shell {
|
||||
width: 100%;
|
||||
height: 100dvh;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.app-content {
|
||||
grid-template-columns: 280px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.messages,
|
||||
.conversation-header {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.message {
|
||||
max-width: 95%;
|
||||
}
|
||||
|
||||
.message-meta {
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.composer {
|
||||
padding: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 620px) {
|
||||
.app-shell {
|
||||
height: auto;
|
||||
min-height: 100dvh;
|
||||
}
|
||||
|
||||
.app-header {
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
.brand {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.account .avatar,
|
||||
.account small {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.account {
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.app-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.sidebar-heading {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.chat-list {
|
||||
max-height: 240px;
|
||||
}
|
||||
|
||||
.sidebar .pagination {
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
.sidebar .page-settings,
|
||||
.sidebar .page-navigation {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.sidebar .page-range {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.conversation {
|
||||
min-height: 480px;
|
||||
}
|
||||
|
||||
.messages {
|
||||
max-height: 55dvh;
|
||||
min-height: 180px;
|
||||
}
|
||||
|
||||
.pagination {
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.composer {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.composer .primary {
|
||||
padding: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* {
|
||||
transition: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
.composer-fields {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.composer-fields textarea {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.file-picker {
|
||||
display: block;
|
||||
margin-top: 10px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.file-picker input {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.upload-list {
|
||||
list-style: none;
|
||||
margin: 8px 0 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.upload-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.upload-list li span {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.attachment-image {
|
||||
margin: 10px 0 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.attachment-image img {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
max-height: 320px;
|
||||
object-fit: contain;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.attachment-image figcaption {
|
||||
margin-top: 6px;
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.composer {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.composer-fields {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.upload-list li {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
|
||||
.upload-method {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.upload-method select {
|
||||
max-width: 100%;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
background: #fafbf8;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
@@ -3,53 +3,53 @@ import type { Page } from "./api";
|
||||
|
||||
// The API supplies only a next cursor. Remember visited cursors for Back.
|
||||
export function useCursorPage<T>(
|
||||
resource: string,
|
||||
fetchPage: (cursor: string | undefined, limit: number) => Promise<Page<T>>,
|
||||
onError: (error: unknown) => void,
|
||||
resource: string,
|
||||
fetchPage: (cursor: string | undefined, limit: number) => Promise<Page<T>>,
|
||||
onError: (error: unknown) => void,
|
||||
) {
|
||||
const [query, setQuery] = useState({ resource, cursors: [""], index: 0, size: 5, revision: 0 });
|
||||
const current = query.resource === resource ? query : { ...query, resource, cursors: [""], index: 0 };
|
||||
const cursor = current.cursors[current.index];
|
||||
const queryKey = JSON.stringify([resource, cursor, current.index, current.size, current.revision]);
|
||||
const [result, setResult] = useState<{ key: string; page: Page<T>; busy: boolean; failed: boolean }>({
|
||||
key: "", page: { items: [], next_cursor: null }, busy: false, failed: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!resource) return;
|
||||
let active = true;
|
||||
setResult({ key: queryKey, page: { items: [], next_cursor: null }, busy: true, failed: false });
|
||||
fetchPage(cursor || undefined, current.size).then((page) => {
|
||||
if (active) setResult({ key: queryKey, page, busy: false, failed: false });
|
||||
}).catch((error: unknown) => {
|
||||
if (!active) return;
|
||||
setResult({ key: queryKey, page: { items: [], next_cursor: null }, busy: false, failed: true });
|
||||
onError(error);
|
||||
const [query, setQuery] = useState({ resource, cursors: [""], index: 0, size: 5, revision: 0 });
|
||||
const current = query.resource === resource ? query : { ...query, resource, cursors: [""], index: 0 };
|
||||
const cursor = current.cursors[current.index];
|
||||
const queryKey = JSON.stringify([resource, cursor, current.index, current.size, current.revision]);
|
||||
const [result, setResult] = useState<{ key: string; page: Page<T>; busy: boolean; failed: boolean }>({
|
||||
key: "", page: { items: [], next_cursor: null }, busy: false, failed: false,
|
||||
});
|
||||
return () => { active = false; };
|
||||
}, [resource, queryKey, cursor, current.size, fetchPage, onError]);
|
||||
|
||||
const matches = result.key === queryKey;
|
||||
const items = matches ? result.page.items : [];
|
||||
const busy = Boolean(resource) && (!matches || result.busy);
|
||||
const nextCursor = matches ? result.page.next_cursor : null;
|
||||
useEffect(() => {
|
||||
if (!resource) return;
|
||||
let active = true;
|
||||
setResult({ key: queryKey, page: { items: [], next_cursor: null }, busy: true, failed: false });
|
||||
fetchPage(cursor || undefined, current.size).then((page) => {
|
||||
if (active) setResult({ key: queryKey, page, busy: false, failed: false });
|
||||
}).catch((error: unknown) => {
|
||||
if (!active) return;
|
||||
setResult({ key: queryKey, page: { items: [], next_cursor: null }, busy: false, failed: true });
|
||||
onError(error);
|
||||
});
|
||||
return () => { active = false; };
|
||||
}, [resource, queryKey, cursor, current.size, fetchPage, onError]);
|
||||
|
||||
return {
|
||||
items, busy, failed: matches && result.failed,
|
||||
number: current.index + 1,
|
||||
size: current.size,
|
||||
hasPrevious: current.index > 0,
|
||||
hasNext: Boolean(nextCursor),
|
||||
range: items.length ? `${current.index * current.size + 1}–${current.index * current.size + items.length}` : "0",
|
||||
next() {
|
||||
if (!nextCursor || busy) return;
|
||||
setQuery({ ...current, cursors: [...current.cursors.slice(0, current.index + 1), nextCursor], index: current.index + 1 });
|
||||
},
|
||||
previous() {
|
||||
if (current.index > 0 && !busy) setQuery({ ...current, index: current.index - 1 });
|
||||
},
|
||||
resize(size: number) { setQuery({ ...current, size, index: 0, cursors: [""] }); },
|
||||
refresh() { setQuery({ ...current, index: 0, cursors: [""], revision: current.revision + 1 }); },
|
||||
reload() { setQuery({ ...current, revision: current.revision + 1 }); },
|
||||
};
|
||||
const matches = result.key === queryKey;
|
||||
const items = matches ? result.page.items : [];
|
||||
const busy = Boolean(resource) && (!matches || result.busy);
|
||||
const nextCursor = matches ? result.page.next_cursor : null;
|
||||
|
||||
return {
|
||||
items, busy, failed: matches && result.failed,
|
||||
number: current.index + 1,
|
||||
size: current.size,
|
||||
hasPrevious: current.index > 0,
|
||||
hasNext: Boolean(nextCursor),
|
||||
range: items.length ? `${current.index * current.size + 1}–${current.index * current.size + items.length}` : "0",
|
||||
next() {
|
||||
if (!nextCursor || busy) return;
|
||||
setQuery({ ...current, cursors: [...current.cursors.slice(0, current.index + 1), nextCursor], index: current.index + 1 });
|
||||
},
|
||||
previous() {
|
||||
if (current.index > 0 && !busy) setQuery({ ...current, index: current.index - 1 });
|
||||
},
|
||||
resize(size: number) { setQuery({ ...current, size, index: 0, cursors: [""] }); },
|
||||
refresh() { setQuery({ ...current, index: 0, cursors: [""], revision: current.revision + 1 }); },
|
||||
reload() { setQuery({ ...current, revision: current.revision + 1 }); },
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user