feat: add minio

This commit is contained in:
TAskMAster339
2026-10-18 18:06:27 +03:00
parent 9bbd342756
commit e3cd2516ba
30 changed files with 1213 additions and 177 deletions
+8 -1
View File
@@ -5,7 +5,7 @@ ACTION_SCRIPT ?=
COMPOSE = docker compose --project-name highload-lab4 --env-file .env -f compose.yml
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence test-failover
.PHONY: help check validate test load test-persistence test-failover test-grade3 test-grade3-failures
.PHONY: app-init app-build app-up app-start app-stop app-down app-restart app-logs app-status test-backend test-baseline test-baseline-persistence
help:
@@ -13,6 +13,7 @@ help:
@echo "app-start: start without rebuilding; app-stop: stop and keep containers"
@echo "app-down: remove containers and networks, keeping data volumes"
@echo "app-restart: restart the stack; app-logs / app-status: inspect services"
@echo "test-grade3 / test-grade3-failures: attachment checks; second target temporarily stops this stack services"
@echo "test-backend: Go race tests; test-baseline: transferred API checks"
@echo "test-baseline-persistence: transferred API checks across a restart"
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@@ -54,6 +55,12 @@ test-baseline:
test-baseline-persistence:
$(PYTHON) scripts/check_baseline.py --base-url "$(BASE_URL)" --restart
test-grade3:
$(PYTHON) scripts/check_grade3.py --base-url "$(BASE_URL)"
test-grade3-failures:
$(PYTHON) scripts/check_grade3.py --base-url "$(BASE_URL)" --failures
check:
$(PYTHON) scripts/check_contract.py
+46 -1
View File
@@ -53,17 +53,57 @@ services:
depends_on:
db:
condition: service_healthy
api:
s3:
cpus: 1.0
mem_limit: 512m
networks: [data]
build:
context: ./infra
dockerfile: minio.Dockerfile
environment:
MINIO_ROOT_USER_FILE: /run/secrets/s3_access_key_id
MINIO_ROOT_PASSWORD_FILE: /run/secrets/s3_secret_access_key
MINIO_BROWSER: "off"
volumes:
- s3_data:/data
- ./secrets/s3_access_key_id:/run/secrets/s3_access_key_id:ro
- ./secrets/s3_secret_access_key:/run/secrets/s3_secret_access_key:ro
healthcheck:
test: ["CMD", "curl", "-f", "http://127.0.0.1:9000/minio/health/ready"]
interval: 3s
timeout: 2s
retries: 30
s3-bootstrap:
cpus: 0.5
mem_limit: 128m
networks: [data]
build: ./src
environment: &s3-environment
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3: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}
S3_SECRET_ACCESS_KEY_FILE: ${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key}
volumes:
- ./secrets/s3_access_key_id:${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id}:ro
- ./secrets/s3_secret_access_key:${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key}:ro
command: ["./messenger", "s3-bootstrap"]
depends_on:
s3:
condition: service_healthy
api:
cpus: 0.5
mem_limit: 512m
networks: [proxy, data]
build: ./src
deploy:
replicas: ${API_REPLICAS:-2}
stop_grace_period: 15s
environment:
<<: *s3-environment
# Go 1.22 sees host CPUs; keep parallelism suitable for this 0.5 CPU limit.
GOMAXPROCS: ${API_GOMAXPROCS:-1}
GOMEMLIMIT: 384MiB
APP_HOST: ${APP_HOST:-0.0.0.0}
APP_PORT: ${APP_PORT:-8080}
APP_ENV: ${APP_ENV:-lab}
@@ -74,9 +114,13 @@ services:
REDIS_ADDR: redis:6379
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
volumes:
- ./secrets/s3_access_key_id:${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id}:ro
- ./secrets/s3_secret_access_key:${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key}:ro
- ./secrets/database_url:${DATABASE_URL_FILE:-/run/secrets/database_url}:ro
- ./secrets/cache_url:${CACHE_URL_FILE:-/run/secrets/cache_url}:ro
depends_on:
s3-bootstrap:
condition: service_completed_successfully
migrate:
condition: service_completed_successfully
db:
@@ -165,6 +209,7 @@ services:
volumes:
postgres_data:
redis_data:
s3_data:
networks:
edge:
+2 -2
View File
@@ -9,8 +9,8 @@ defaults
mode http
option httplog
timeout connect 1s
timeout client 15s
timeout server 12s
timeout client 35s
timeout server 35s
timeout check 1s
# Let the client decide which failed POST is safe to repeat.
retries 0
+19
View File
@@ -0,0 +1,19 @@
FROM golang:1.24.2-bookworm AS builder
WORKDIR /source
RUN git init . \
&& git remote add origin https://github.com/minio/minio.git \
&& git fetch --depth 1 origin 0d7408fc9969caf07de6a8c3a84f9fbb10a6739e \
&& git checkout --detach FETCH_HEAD
RUN CGO_ENABLED=0 go build -trimpath \
-ldflags="-s -w -X github.com/minio/minio/cmd.Version=2025-04-22T22:12:26Z -X github.com/minio/minio/cmd.ReleaseTag=RELEASE.2025-04-22T22-12-26Z -X github.com/minio/minio/cmd.CommitID=0d7408fc9969caf07de6a8c3a84f9fbb10a6739e" \
-o /out/minio .
FROM debian:12.15-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl \
&& rm -rf /var/lib/apt/lists/* \
&& groupadd --system storage && useradd --system --gid storage storage \
&& mkdir /data && chown storage:storage /data
COPY --from=builder /out/minio /usr/local/bin/minio
USER storage:storage
ENTRYPOINT ["minio"]
CMD ["server", "/data", "--console-address", ":9001"]
+165
View File
@@ -0,0 +1,165 @@
import argparse
import base64
import concurrent.futures
import hashlib
import http.client
import json
import os
import struct
import subprocess
import sys
import time
import urllib.parse
import uuid
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check, run
COMPOSE = ["docker", "compose", "--project-name", "highload-lab4", "--env-file", ".env", "-f", "compose.yml"]
def command(args, **kwargs):
return subprocess.check_output(args, cwd=ROOT, text=True, **kwargs).strip()
def ready(client):
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Exception:
time.sleep(1)
raise AssertionError("readiness did not recover")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--failures", action="store_true")
args = parser.parse_args()
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
png = (ROOT / "tests/fixtures/sample.png").read_bytes()
path = "/api/v1/chats/" + chat["id"] + "/attachments"
def upload(data=png, mime="image/png", filename="photo.png", status=201, actor=alice, target=path):
return c.call("POST", target + "?" + urllib.parse.urlencode({"filename": filename}), status,
actor=actor, raw=data, headers={"Content-Type": mime}, schema="Attachment" if status == 201 else None)
jpeg = base64.b64decode('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAACAAMDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDj6KKKyPJP/9k=')
jpeg_result = upload(data=jpeg,mime="image/jpeg",filename="photo.jpg")["json"]
check(c.call("GET", "/api/v1/attachments/"+jpeg_result["id"]+"/content",actor=bob)["bytes"] == jpeg,"JPEG changed")
first = upload()["json"]
second = upload(filename="Второе фото.png")["json"]
for a in (first, second):
content = c.call("GET", "/api/v1/attachments/" + a["id"] + "/content", actor=bob)
check(content["bytes"] == png, "download bytes changed")
check(a["sha256"] == hashlib.sha256(png).hexdigest(), "checksum differs")
for suffix in ("", "/content"):
c.call("GET", "/api/v1/attachments/" + first["id"] + suffix, 404, actor=eve)
c.call("GET", "/api/v1/attachments/" + first["id"] + suffix, 401)
c.call("GET", "/api/v1/attachments/" + first["id"] + "/content?variant=thumbnail", 404, actor=alice)
upload(actor=eve, status=404)
upload(data=b"x" * (10485760 + 1), status=413)
upload(data=png[:40], status=415)
upload(mime="image/jpeg", status=415)
upload(mime="text/plain", status=415)
for filename in ("", " ", "../file.png", "a\\b.png", "a\x00.png", "a\n.png", "x" * 256):
upload(filename=filename, status=400)
huge = bytearray(png)
huge[16:24] = struct.pack(">II", 10001, 4000)
huge[29:33] = struct.pack(">I", zlib.crc32(huge[12:29]) & 0xffffffff)
upload(data=bytes(huge), status=413)
# Unknown-length uploads must obey the same byte limit.
endpoint = urllib.parse.urlsplit(args.base_url)
conn = http.client.HTTPConnection(endpoint.hostname, endpoint.port or 80, timeout=35)
conn.request("POST", path + "?filename=chunked.png", body=iter([png, b"x" * 10485760]),
headers={"Authorization": "Bearer " + alice["token"], "Content-Type": "image/png"}, encode_chunked=True)
response = conn.getresponse()
check(response.status == 413, "chunked body limit not enforced")
response.read(); conn.close()
ids = [first["id"], second["id"]]
key = uuid.uuid4().hex
def send(_):
return c.message(alice, chat, "", key=key, attachments=ids)
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
responses = list(pool.map(send, range(24)))
check(len({r["headers"]["X-Instance-Id"] for r in responses}) >= 2, "did not use two API replicas")
check(all(r["json"] == responses[0]["json"] for r in responses), "replay changed message")
messages_path = "/api/v1/chats/" + chat["id"] + "/messages"
history = c.call("GET", messages_path, actor=bob, schema="MessagePage")["json"]["items"]
check(len(history) == 1 and history[0]["attachment_ids"] == ids, "duplicate or lost attachments")
for body, expected in (({"text": "", "attachment_ids": ids[::-1]}, 409),
({"text": "changed", "attachment_ids": ids}, 409)):
c.call("POST", messages_path, expected, actor=alice, body=body, headers={"Idempotency-Key": key})
for bad_ids, expected in (([first["id"], first["id"]], 400), ([str(uuid.uuid4())], 404), (["invalid"], 400), (None, 400), (ids * 6, 400)):
c.call("POST", messages_path, expected, actor=alice, body={"text": "x", "attachment_ids": bad_ids}, headers={"Idempotency-Key": uuid.uuid4().hex})
other_chat = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "Other", "member_ids": [alice["id"]]}, schema="Chat")["json"]
c.call("POST", "/api/v1/chats/" + other_chat["id"] + "/messages", 404, actor=alice,
body={"text": "", "attachment_ids": [first["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
text_key = uuid.uuid4().hex
text = c.message(alice, chat, "text", key=text_key)["json"]
check(c.message(alice, chat, "text", key=text_key, attachments=[])["json"] == text, "omitted/empty array differ")
print("PASS: image limits, chunked upload, ACL, message attachments, concurrent replay across replicas")
if args.failures:
records = []
for _ in range(2):
result = upload()
target = result["headers"]["X-Instance-Id"]
a = result["json"]
check(not records or target != records[0]["upload_instance"], "repeat did not target the other replica")
try:
command([str(ROOT / "scripts/stop-one.sh")], env={**os.environ, "TARGET_INSTANCE_ID": target})
time.sleep(3)
downloaded = c.call("GET", "/api/v1/attachments/" + a["id"] + "/content", actor=bob)
check(downloaded["bytes"] == png, "original lost across failover")
served = downloaded["headers"]["X-Instance-Id"]
check(served != target, "download came from stopped instance")
records.append({"upload_instance": target, "download_instance": served, "sha256": a["sha256"]})
if len(records) == 1:
# Upload the next fixture while only the second replica runs.
# Restore below, then select that same replica via LB uploads.
next_target = served
finally:
command(COMPOSE + ["up", "-d", "--no-build", "--wait"], stderr=subprocess.STDOUT)
ready(c)
if len(records) == 1:
# Round-robin state may change after recovery; keep requesting until it
# chooses the other replica, then use that upload in the next pass.
original_upload = upload
def upload(*a, **kw):
for attempt in range(30):
candidate = original_upload(*a, **kw)
if candidate["headers"]["X-Instance-Id"] == next_target:
return candidate
raise AssertionError("could not reach second replica")
print("PASS: stop the uploading replica, download from the other (both replicas)")
try:
command(COMPOSE + ["stop", "s3"], stderr=subprocess.STDOUT)
# Probe through an existing image on the data network; no API port exposure.
image = command(["docker", "inspect", "--format", "{{.Config.Image}}", command(COMPOSE + ["ps", "--all", "-q", "s3"])])
probe = ["docker", "run", "--rm", "--network", "highload-lab4_data", "--entrypoint", "curl", image, "-s", "-o", "/dev/null", "-w", "%{http_code}"]
for container in command(COMPOSE + ["ps", "-q", "api"]).splitlines():
# Container hostname aliases are not DNS names; use the data-network IP.
info = json.loads(command(["docker", "inspect", container]))[0]
ip = info["NetworkSettings"]["Networks"]["highload-lab4_data"]["IPAddress"]
check(command(probe + [f"http://{ip}:8080/health/live"]) == "200", "liveness depends on S3")
check(command(probe + [f"http://{ip}:8080/health/ready"]) == "503", "readiness ignores S3 failure")
records.append({"s3_failure": "live=200 ready=503 on both API replicas"})
finally:
command(COMPOSE + ["up", "-d", "--no-build", "--wait"], stderr=subprocess.STDOUT)
ready(c)
check(c.call("GET", "/api/v1/attachments/" + first["id"] + "/content", actor=bob)["bytes"] == png, "S3 recovery lost bytes")
image = command(["docker", "inspect", "--format", "{{.Config.Image}}", command(COMPOSE + ["ps", "--all", "-q", "s3"])])
code = command(["docker", "run", "--rm", "--network", "highload-lab4_data", "--entrypoint", "curl", image, "-s", "-o", "/dev/null", "-w", "%{http_code}", "http://s3:9000/messenger-attachments/originals/" + first["id"]])
check(code == "403", "anonymous object access was permitted")
records.append({"anonymous_object_get": code})
directory = ROOT / ".memory/grade3"
directory.mkdir(parents=True, exist_ok=True)
(directory / "failures.json").write_text(json.dumps(records, indent=2) + "\n")
print("PASS: S3 unavailable/recovery, private bucket")
if __name__ == "__main__":
run(main)
+4 -2
View File
@@ -47,11 +47,13 @@ def main():
quote(values["POSTGRES_USER"], safe=""), quote(values["POSTGRES_PASSWORD"], safe=""),
quote(values["POSTGRES_DB"], safe=""))
for name, content in (("DATABASE_URL_FILE", database_url),
("CACHE_URL_FILE", "redis://redis:6379/0")):
("CACHE_URL_FILE", "redis://redis:6379/0"),
("S3_ACCESS_KEY_ID_FILE", secrets.token_hex(12)),
("S3_SECRET_ACCESS_KEY_FILE", secrets.token_hex(32))):
container_path = Path(values[name])
if container_path.parent != Path("/run/secrets") or not container_path.name:
raise SystemExit(f"{name} must name a file directly inside /run/secrets")
target = secret_dir / ("database_url" if name == "DATABASE_URL_FILE" else "cache_url")
target = secret_dir / {"DATABASE_URL_FILE":"database_url", "CACHE_URL_FILE":"cache_url", "S3_ACCESS_KEY_ID_FILE":"s3_access_key_id", "S3_SECRET_ACCESS_KEY_FILE":"s3_secret_access_key"}[name]
if not target.exists():
# Containers run as an unprivileged user; the private host directory
# protects the files, while read permission lets the API consume them.
+2 -2
View File
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose --project-name highload-lab4 --env-file .env -f compose.yml restart db redis >/dev/null
docker compose --project-name highload-lab4 --env-file .env -f compose.yml up -d --wait db redis >/dev/null
docker compose --project-name highload-lab4 --env-file .env -f compose.yml restart db redis s3 >/dev/null
docker compose --project-name highload-lab4 --env-file .env -f compose.yml up -d --wait db redis s3 >/dev/null
docker compose --project-name highload-lab4 --env-file .env -f compose.yml restart api >/dev/null
docker compose --project-name highload-lab4 --env-file .env -f compose.yml up -d --wait >/dev/null
+145
View File
@@ -0,0 +1,145 @@
package handlers
import (
"context"
"errors"
"github.com/google/uuid"
"io"
"log"
"messenger/src/backend/services"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
func uploadAttachmentHandler(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
}
userID, ok := requestUserID(w, r, requestID)
if !ok {
return
}
raw := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/api/v1/chats/"), "/attachments")
chatID, err := uuid.Parse(raw)
if err != nil {
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
return
}
if _, err = chats.Get(r.Context(), userID, chatID.String()); err != nil {
writeServiceError(w, err, requestID)
return
}
query, err := urlQuery(r)
if err != nil {
writeServiceError(w, err, requestID)
return
}
filenames := query["filename"]
if len(filenames) != 1 {
writeError(w, 400, "invalid_request", "exactly one filename is required", requestID)
return
}
if err = services.ValidateFilename(filenames[0]); err != nil {
writeServiceError(w, err, requestID)
return
}
if r.ContentLength > services.MaxUploadBytes {
writeServiceError(w, services.ErrPayloadTooLarge, requestID)
return
}
r.Body = http.MaxBytesReader(w, r.Body, services.MaxUploadBytes)
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
attachment, err := attachments.Upload(ctx, userID, chatID.String(), filenames[0], r.Header.Get("Content-Type"), r.Body)
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
err = services.ErrPayloadTooLarge
}
if err != nil {
writeServiceError(w, err, requestID)
return
}
writeJSON(w, 201, attachment)
}
}
func attachmentHandler(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.MethodGet {
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
return
}
userID, ok := requestUserID(w, r, requestID)
if !ok {
return
}
path := strings.TrimPrefix(r.URL.Path, "/api/v1/attachments/")
parts := strings.Split(path, "/")
if len(parts) > 2 || (len(parts) == 2 && parts[1] != "content") {
writeServiceError(w, services.ErrAttachmentNotFound, requestID)
return
}
id, err := uuid.Parse(parts[0])
if err != nil {
writeError(w, 400, "invalid_request", "invalid attachment id", requestID)
return
}
a, err := attachments.Get(r.Context(), id.String(), userID)
if err != nil {
writeServiceError(w, err, requestID)
return
}
if len(parts) == 1 {
writeJSON(w, 200, a)
return
}
query, err := urlQuery(r)
if err != nil {
writeServiceError(w, err, requestID)
return
}
if variants, exists := query["variant"]; exists {
if len(variants) != 1 {
writeError(w, 400, "invalid_request", "invalid variant", requestID)
return
}
if variants[0] != "original" {
writeServiceError(w, services.ErrAttachmentNotFound, requestID)
return
}
}
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
content, err := attachments.Content(ctx, a)
if err != nil {
writeServiceError(w, err, requestID)
return
}
defer content.Close()
w.Header().Set("Content-Type", a.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(a.SizeBytes, 10))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "private, no-store")
w.WriteHeader(200)
if _, err = io.Copy(w, content); err != nil {
log.Printf("attachment download interrupted, request %s", requestID)
}
}
}
func urlQuery(r *http.Request) (url.Values, error) {
q, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return nil, services.InvalidInput{Message: "invalid query"}
}
return q, nil
}
+5 -1
View File
@@ -110,11 +110,15 @@ func chatCollectionHandler(chats *services.ChatService) http.HandlerFunc {
}
}
func chatSubresourceHandler(chats *services.ChatService, messages *services.MessageService) http.HandlerFunc {
func chatSubresourceHandler(chats *services.ChatService, messages *services.MessageService, attachments *services.AttachmentService) http.HandlerFunc {
get := getChatHandler(chats)
createMessage := createMessageHandler(chats, messages)
listMessages := listMessagesHandler(chats, messages)
return func(w http.ResponseWriter, r *http.Request) {
if attachments != nil && strings.HasSuffix(r.URL.Path, "/attachments") {
uploadAttachmentHandler(chats, attachments)(w, r)
return
}
if strings.HasSuffix(r.URL.Path, "/messages") {
if r.Method == http.MethodGet {
listMessages(w, r)
+15 -2
View File
@@ -48,6 +48,12 @@ func writeServiceError(w http.ResponseWriter, err error, requestID string) {
switch {
case errors.As(err, &invalid):
writeError(w, 400, "invalid_request", invalid.Message, requestID)
case errors.Is(err, services.ErrPayloadTooLarge):
writeError(w, 413, "payload_too_large", "image exceeds upload limits", requestID)
case errors.Is(err, services.ErrUnsupportedMedia):
writeError(w, 415, "unsupported_media_type", "a valid PNG or JPEG matching Content-Type is required", requestID)
case errors.Is(err, services.ErrAttachmentNotFound):
writeError(w, 404, "not_found", "attachment not found", requestID)
case errors.Is(err, services.ErrConflict):
writeError(w, 409, "conflict", "request conflicts with an existing resource", requestID)
case errors.Is(err, services.ErrUnknownUser):
@@ -130,7 +136,11 @@ func readyHandler(health *services.HealthService) http.HandlerFunc {
}
}
func NewRouter(health *services.HealthService, users *services.UserService, sessions *services.SessionService, chats *services.ChatService, messages *services.MessageService) http.Handler {
func NewRouter(health *services.HealthService, users *services.UserService, sessions *services.SessionService, chats *services.ChatService, messages *services.MessageService, attachmentServices ...*services.AttachmentService) http.Handler {
var attachments *services.AttachmentService
if len(attachmentServices) > 0 {
attachments = attachmentServices[0]
}
mux := http.NewServeMux()
mux.HandleFunc("/health/live", healthHandler)
mux.HandleFunc("/health/ready", readyHandler(health))
@@ -139,6 +149,9 @@ func NewRouter(health *services.HealthService, users *services.UserService, sess
mux.Handle("/api/v1/auth/sessions/current", authRequired(sessions, logoutHandler(sessions)))
mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(users)))
mux.Handle("/api/v1/chats", authRequired(sessions, chatCollectionHandler(chats)))
mux.Handle("/api/v1/chats/", authRequired(sessions, chatSubresourceHandler(chats, messages)))
mux.Handle("/api/v1/chats/", authRequired(sessions, chatSubresourceHandler(chats, messages, attachments)))
if attachments != nil {
mux.Handle("/api/v1/attachments/", authRequired(sessions, attachmentHandler(attachments)))
}
return withInstance(mux)
}
+9 -5
View File
@@ -10,7 +10,7 @@ import (
)
type createMessageRequest struct {
Text string `json:"text"`
Text *string `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
}
@@ -62,10 +62,14 @@ func createMessageHandler(chats *services.ChatService, messages *services.Messag
writeError(w, 400, "invalid_request", "invalid JSON body", requestID)
return
}
ids := []string{}
if request.Text == nil {
writeError(w, 400, "invalid_request", "text must be a string", requestID)
return
}
if len(request.AttachmentIDs) > 0 {
var ids []string
if err := json.Unmarshal(request.AttachmentIDs, &ids); err != nil || ids == nil || len(ids) != 0 {
writeError(w, 400, "invalid_request", "attachments are not supported in lab3; use an empty array or omit attachment_ids", requestID)
if err := json.Unmarshal(request.AttachmentIDs, &ids); err != nil || ids == nil {
writeError(w, 400, "invalid_request", "attachment_ids must be an array of UUIDs", requestID)
return
}
}
@@ -74,7 +78,7 @@ func createMessageHandler(chats *services.ChatService, messages *services.Messag
writeError(w, 400, "invalid_request", "exactly one Idempotency-Key is required", requestID)
return
}
message, err := messages.CreateIdempotent(r.Context(), userID, chat, request.Text, keys[0])
message, err := messages.CreateIdempotent(r.Context(), userID, chat, *request.Text, keys[0], ids)
if err != nil {
writeServiceError(w, err, requestID)
return
+21 -3
View File
@@ -35,6 +35,19 @@ func main() {
if environment := os.Getenv("APP_ENV"); environment != "" {
log.SetPrefix("[" + environment + "] ")
}
if len(os.Args) == 2 && os.Args[1] == "s3-bootstrap" {
objects, err := repositories.NewObjectStoreFromEnvironment()
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err = objects.Bootstrap(ctx); err != nil {
log.Fatal("S3 bootstrap failed")
}
log.Print("private S3 bucket ready")
return
}
if len(os.Args) > 1 {
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
client := http.Client{Timeout: 2 * time.Second}
@@ -109,14 +122,19 @@ func main() {
sessionService := services.NewSessionService(userService, sessionStore, ttl)
chatService := services.NewChatService(chatStore)
messageService := services.NewMessageService(messageStore)
mux := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db), sessionStore), userService, sessionService, chatService, messageService)
objects, err := repositories.NewObjectStoreFromEnvironment()
if err != nil {
log.Fatal(err)
}
attachmentService := services.NewAttachmentService(repositories.NewAttachmentStore(db), objects)
mux := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db), sessionStore, objects), userService, sessionService, chatService, messageService, attachmentService)
server := &http.Server{
Addr: serverAddress(),
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
+42
View File
@@ -0,0 +1,42 @@
package repositories
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
"time"
)
type Attachment struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ObjectKey string `json:"-"`
}
type AttachmentStore struct{ db *pgxpool.Pool }
func NewAttachmentStore(db *pgxpool.Pool) *AttachmentStore { return &AttachmentStore{db: db} }
func (s *AttachmentStore) Create(ctx context.Context, a Attachment) error {
ctx, cancel := boundedQuery(ctx)
defer cancel()
_, err := s.db.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)
return err
}
func (s *AttachmentStore) GetForMember(ctx context.Context, id, userID string) (Attachment, error) {
ctx, cancel := boundedQuery(ctx)
defer cancel()
a := Attachment{Status: "ready", Variants: []any{}}
err := s.db.QueryRow(ctx, `SELECT a.id,a.chat_id,a.owner_id,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.created_at,a.updated_at FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id WHERE a.id=$1 AND cm.user_id=$2`, id, userID).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.CreatedAt, &a.UpdatedAt)
a.CreatedAt = a.CreatedAt.UTC()
a.UpdatedAt = a.UpdatedAt.UTC()
return a, err
}
+27 -5
View File
@@ -3,16 +3,23 @@ package repositories
import (
"context"
"errors"
"reflect"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
var ErrAttachmentNotFound = errors.New("attachment not found")
var ErrIdempotencyConflict = errors.New("idempotency key belongs to a different message")
// CreateIdempotent commits the message and its replay record together.
func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, text, key string) (Message, error) {
func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, text, key string, attachments ...[]string) (Message, error) {
ids := []string{}
if len(attachments) > 0 && attachments[0] != nil {
ids = attachments[0]
}
ctx, cancel := boundedQuery(ctx)
defer cancel()
tx, err := s.db.Begin(ctx)
@@ -27,16 +34,26 @@ func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, t
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", scope); err != nil {
return Message{}, err
}
// Validate attachments in this same transaction, including replay.
for _, id := range ids {
var exists bool
if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachments WHERE id=$1 AND chat_id=$2)", id, chatID).Scan(&exists); err != nil {
return Message{}, err
}
if !exists {
return Message{}, ErrAttachmentNotFound
}
}
var message Message
err = tx.QueryRow(ctx, `
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, ARRAY(SELECT attachment_id::text FROM message_attachments ma WHERE ma.message_id=m.id ORDER BY position)
FROM message_idempotency i JOIN messages m ON m.id = i.message_id
WHERE i.sender_id=$1 AND i.chat_id=$2 AND i.key=$3
AND i.expires_at > clock_timestamp()`, senderID, chatID, key).
Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt)
Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt, &message.AttachmentIDs)
if err == nil {
message.CreatedAt = message.CreatedAt.UTC()
if message.Text != text {
if message.Text != text || !reflect.DeepEqual(message.AttachmentIDs, ids) {
return Message{}, ErrIdempotencyConflict
}
return message, tx.Commit(ctx)
@@ -50,12 +67,17 @@ func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, t
return Message{}, err
}
message = Message{
ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text,
AttachmentIDs: ids, ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text,
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
}
if _, err = tx.Exec(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", message.ID, chatID, senderID, text, message.CreatedAt); err != nil {
return Message{}, err
}
for position, id := range ids {
if _, err = tx.Exec(ctx, "INSERT INTO message_attachments(message_id,attachment_id,position) VALUES($1,$2,$3)", message.ID, id, position); err != nil {
return Message{}, err
}
}
if _, err = tx.Exec(ctx, `INSERT INTO message_idempotency(sender_id,chat_id,key,message_id,expires_at)
VALUES($1,$2,$3,$4,clock_timestamp() + $5 * interval '1 second')`, senderID, chatID, key, message.ID, s.idempotencyTTL.Seconds()); err != nil {
return Message{}, err
+14 -12
View File
@@ -9,11 +9,12 @@ import (
)
type Message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
type MessageStore struct {
@@ -38,11 +39,12 @@ func (s *MessageStore) Create(
ctx, cancel := boundedQuery(ctx)
defer cancel()
message := Message{
ID: uuid.New().String(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
AttachmentIDs: []string{},
ID: uuid.New().String(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
}
_, err := s.db.Exec(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt)
@@ -63,7 +65,7 @@ func (s *MessageStore) ListPageByChat(
afterTime = cursor.CreatedAt
afterID = cursor.MessageID
}
rows, err := s.db.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3::uuid) ORDER BY created_at,id LIMIT $4`, chatID, afterTime, afterID, limit+1)
rows, err := s.db.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at,ARRAY(SELECT attachment_id::text FROM message_attachments ma WHERE ma.message_id=messages.id ORDER BY position) FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3::uuid) ORDER BY created_at,id LIMIT $4`, chatID, afterTime, afterID, limit+1)
if err != nil {
return nil, false, err
}
@@ -71,7 +73,7 @@ func (s *MessageStore) ListPageByChat(
items := []Message{}
for rows.Next() {
var m Message
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs); err != nil {
return nil, false, err
}
items = append(items, m)
@@ -0,0 +1,5 @@
-- An operator must first remove attachment-only messages before this rollback.
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE messages ADD CONSTRAINT messages_text_check CHECK (char_length(text) BETWEEN 1 AND 4000);
DROP TABLE message_attachments;
DROP TABLE attachments;
@@ -0,0 +1,22 @@
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id),
owner_id uuid NOT NULL REFERENCES users(id),
filename text NOT NULL,
object_key text NOT NULL UNIQUE,
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}$'),
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL
);
CREATE INDEX attachments_chat_idx ON attachments(chat_id);
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
attachment_id uuid NOT NULL REFERENCES attachments(id),
position smallint NOT NULL CHECK (position BETWEEN 0 AND 9),
PRIMARY KEY (message_id, attachment_id),
UNIQUE(message_id, position)
);
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE messages ADD CONSTRAINT messages_text_check CHECK (char_length(text) <= 4000);
+99
View File
@@ -0,0 +1,99 @@
package repositories
import (
"context"
"errors"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
)
type ObjectStore struct {
client *minio.Client
bucket string
}
func NewObjectStoreFromEnvironment() (*ObjectStore, error) {
endpoint, err := url.Parse(os.Getenv("S3_ENDPOINT"))
if err != nil || endpoint.Host == "" || (endpoint.Scheme != "http" && endpoint.Scheme != "https") || endpoint.Path != "" {
return nil, errors.New("invalid S3_ENDPOINT")
}
read := func(name string) (string, error) {
b, e := os.ReadFile(os.Getenv(name))
if e != nil {
return "", errors.New("cannot read " + name)
}
v := strings.TrimSpace(string(b))
if v == "" {
return "", errors.New("empty " + name)
}
return v, nil
}
access, err := read("S3_ACCESS_KEY_ID_FILE")
if err != nil {
return nil, err
}
secret, err := read("S3_SECRET_ACCESS_KEY_FILE")
if err != nil {
return nil, err
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.ResponseHeaderTimeout = 5 * time.Second
transport.MaxIdleConnsPerHost = 8
client, err := minio.New(endpoint.Host, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: endpoint.Scheme == "https", Region: os.Getenv("S3_REGION"), Transport: transport})
if err != nil {
return nil, err
}
bucket := os.Getenv("S3_BUCKET")
if bucket == "" {
return nil, errors.New("S3_BUCKET is required")
}
return &ObjectStore{client: client, bucket: bucket}, nil
}
func (s *ObjectStore) Ping(ctx context.Context) error {
exists, err := s.client.BucketExists(ctx, s.bucket)
if err != nil {
return err
}
if !exists {
return errors.New("bucket missing")
}
return nil
}
func (s *ObjectStore) Bootstrap(ctx context.Context) error {
exists, err := s.client.BucketExists(ctx, s.bucket)
if err != nil {
return err
}
if !exists {
if err = s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: os.Getenv("S3_REGION")}); err != nil {
return err
}
}
// No anonymous policy: every object operation requires signed credentials.
return s.client.SetBucketPolicy(ctx, s.bucket, "")
}
func (s *ObjectStore) Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error {
_, err := s.client.PutObject(ctx, s.bucket, key, body, size, minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true})
return err
}
func (s *ObjectStore) Delete(ctx context.Context, key string) error {
return s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{})
}
func (s *ObjectStore) Get(ctx context.Context, key string) (io.ReadCloser, error) {
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
if err != nil {
return nil, err
}
// GetObject is lazy: force the request before writing HTTP 200 headers.
if _, err = object.Stat(); err != nil {
object.Close()
return nil, err
}
return object, nil
}
+148
View File
@@ -0,0 +1,148 @@
package services
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"log"
"messenger/src/backend/repositories"
"mime"
"strings"
"time"
"unicode"
"unicode/utf8"
)
const MaxUploadBytes int64 = 10485760
const MaxImagePixels int64 = 40000000
var ErrPayloadTooLarge = errors.New("payload too large")
var ErrUnsupportedMedia = errors.New("unsupported image")
var ErrAttachmentNotFound = errors.New("attachment not found")
type AttachmentService struct {
metadata *repositories.AttachmentStore
objects *repositories.ObjectStore
uploadSlot chan struct{}
}
func NewAttachmentService(metadata *repositories.AttachmentStore, objects *repositories.ObjectStore) *AttachmentService {
return &AttachmentService{metadata: metadata, objects: objects, uploadSlot: make(chan struct{}, 1)}
}
func ValidateFilename(name string) error {
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
return InvalidInput{"filename must contain 1-255 characters"}
}
for _, r := range name {
if r == '/' || r == '\\' || unicode.IsControl(r) {
return InvalidInput{"invalid filename"}
}
}
return nil
}
func ValidateImage(data []byte, declared string) (string, error) {
contentType, _, err := mime.ParseMediaType(declared)
if err != nil || (contentType != "image/png" && contentType != "image/jpeg") {
return "", ErrUnsupportedMedia
}
config, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return "", ErrUnsupportedMedia
}
actual := "image/" + format
if actual != contentType {
return "", ErrUnsupportedMedia
}
if config.Width <= 0 || config.Height <= 0 || int64(config.Width) > MaxImagePixels/int64(config.Height) {
return "", ErrPayloadTooLarge
}
// DecodeConfig alone accepts truncated headers; decode only after bounding pixels.
decoded, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return "", ErrUnsupportedMedia
}
_ = decoded
return actual, nil
}
func (s *AttachmentService) Upload(ctx context.Context, userID, chatID, filename, contentType string, body io.Reader) (repositories.Attachment, error) {
select {
case s.uploadSlot <- struct{}{}:
defer func() { <-s.uploadSlot }()
case <-ctx.Done():
return repositories.Attachment{}, ctx.Err()
}
data, err := io.ReadAll(io.LimitReader(body, MaxUploadBytes+1))
if err != nil {
return repositories.Attachment{}, err
}
if int64(len(data)) > MaxUploadBytes {
return repositories.Attachment{}, ErrPayloadTooLarge
}
actual, err := ValidateImage(data, contentType)
if err != nil {
return repositories.Attachment{}, err
}
sum := sha256.Sum256(data)
now := time.Now().UTC().Truncate(time.Microsecond)
a := repositories.Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: filename, ContentType: actual, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:]), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
a.ObjectKey = "originals/" + a.ID
if err = s.objects.Put(ctx, a.ObjectKey, bytes.NewReader(data), a.SizeBytes, a.ContentType); err != nil {
return repositories.Attachment{}, err
}
if err = s.metadata.Create(ctx, a); err != nil {
// A connection error can hide a successful autocommit. Delete only after
// a definite SQL rejection; otherwise preserve bytes for later reconciliation.
var rejected *pgconn.PgError
if errors.As(err, &rejected) {
cleanup, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if cleanupErr := s.objects.Delete(cleanup, a.ObjectKey); cleanupErr != nil {
log.Printf("attachment compensation failed for %s", a.ID)
}
} else {
log.Printf("attachment metadata outcome uncertain for %s; preserving S3 object", a.ID)
}
return repositories.Attachment{}, err
}
return a, nil
}
func (s *AttachmentService) Get(ctx context.Context, id, userID string) (repositories.Attachment, error) {
a, err := s.metadata.GetForMember(ctx, id, userID)
if errors.Is(err, pgx.ErrNoRows) {
return a, ErrAttachmentNotFound
}
return a, err
}
func (s *AttachmentService) Content(ctx context.Context, a repositories.Attachment) (io.ReadCloser, error) {
return s.objects.Get(ctx, a.ObjectKey)
}
func NormalizeAttachmentIDs(ids []string) ([]string, error) {
if len(ids) > 10 {
return nil, InvalidInput{"at most 10 attachments are allowed"}
}
result := make([]string, 0, len(ids))
seen := map[string]bool{}
for _, id := range ids {
parsed, err := uuid.Parse(id)
if err != nil {
return nil, InvalidInput{"invalid attachment id"}
}
id = strings.ToLower(parsed.String())
if seen[id] {
return nil, InvalidInput{"duplicate attachment id"}
}
seen[id] = true
result = append(result, id)
}
return result, nil
}
+14 -3
View File
@@ -9,15 +9,26 @@ import (
type HealthService struct {
health *repositories.HealthStore
sessions *repositories.SessionStore
objects interface{ Ping(context.Context) error }
}
func NewHealthService(health *repositories.HealthStore, sessions *repositories.SessionStore) *HealthService {
return &HealthService{health: health, sessions: sessions}
func NewHealthService(health *repositories.HealthStore, sessions *repositories.SessionStore, objects ...interface{ Ping(context.Context) error }) *HealthService {
service := &HealthService{health: health, sessions: sessions}
if len(objects) > 0 {
service.objects = objects[0]
}
return service
}
func (s *HealthService) Ready(ctx context.Context) error {
if err := s.health.Ping(ctx); err != nil {
return err
}
return s.sessions.Ping(ctx)
if err := s.sessions.Ping(ctx); err != nil {
return err
}
if s.objects != nil {
return s.objects.Ping(ctx)
}
return nil
}
+15 -4
View File
@@ -12,17 +12,28 @@ import (
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (s *MessageService) CreateIdempotent(ctx context.Context, userID string, chat repositories.Chat, text, key string) (repositories.Message, error) {
func (s *MessageService) CreateIdempotent(ctx context.Context, userID string, chat repositories.Chat, text, key string, attachments ...[]string) (repositories.Message, error) {
if !ChatHasMember(chat, userID) {
return repositories.Message{}, ErrChatNotFound
}
if !idempotencyKeyPattern.MatchString(key) {
return repositories.Message{}, InvalidInput{"Idempotency-Key must contain 1-128 ASCII letters, digits or ._:-"}
}
if strings.TrimSpace(text) == "" || utf8.RuneCountInString(text) > 4000 {
return repositories.Message{}, InvalidInput{"text must contain 1-4000 characters and must not be blank"}
var ids []string
if len(attachments) > 0 {
ids = attachments[0]
}
ids, err := NormalizeAttachmentIDs(ids)
if err != nil {
return repositories.Message{}, err
}
if (strings.TrimSpace(text) == "" && len(ids) == 0) || utf8.RuneCountInString(text) > 4000 {
return repositories.Message{}, InvalidInput{"text must be at most 4000 characters; nonblank text or attachments required"}
}
message, err := s.messages.CreateIdempotent(ctx, chat.ID, userID, text, key, ids)
if errors.Is(err, repositories.ErrAttachmentNotFound) {
return repositories.Message{}, ErrAttachmentNotFound
}
message, err := s.messages.CreateIdempotent(ctx, chat.ID, userID, text, key)
if errors.Is(err, repositories.ErrIdempotencyConflict) {
return repositories.Message{}, ErrConflict
}
@@ -0,0 +1,94 @@
package tests
import (
"bytes"
"context"
"encoding/binary"
"errors"
"github.com/google/uuid"
"hash/crc32"
"image"
"image/jpeg"
"image/png"
"messenger/src/backend/repositories"
"messenger/src/backend/services"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestAttachmentImageValidation(t *testing.T) {
img := image.NewRGBA(image.Rect(0, 0, 3, 2))
var pngData, jpegData bytes.Buffer
if err := png.Encode(&pngData, img); err != nil {
t.Fatal(err)
}
if err := jpeg.Encode(&jpegData, img, nil); err != nil {
t.Fatal(err)
}
for _, sample := range []struct {
data []byte
mime string
}{{pngData.Bytes(), "image/png"}, {jpegData.Bytes(), "image/jpeg"}} {
if actual, err := services.ValidateImage(sample.data, sample.mime); err != nil || actual != sample.mime {
t.Fatalf("valid image: %s %v", actual, err)
}
}
huge := append([]byte(nil), pngData.Bytes()...)
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]))
if _, err := services.ValidateImage(huge, "image/png"); !errors.Is(err, services.ErrPayloadTooLarge) {
t.Fatalf("pixel limit: %v", err)
}
for _, sample := range []struct {
data []byte
mime string
}{{pngData.Bytes(), "image/jpeg"}, {jpegData.Bytes(), "image/png"}, {pngData.Bytes()[:40], "image/png"}, {[]byte("not an image"), "image/png"}, {pngData.Bytes(), "text/plain"}} {
if _, err := services.ValidateImage(sample.data, sample.mime); !errors.Is(err, services.ErrUnsupportedMedia) {
t.Fatalf("invalid image accepted: %v", err)
}
}
}
func TestAttachmentFilenameValidation(t *testing.T) {
for _, name := range []string{"", " ", "../photo.png", `a\b.png`, "photo\x00.png", "photo\n.png"} {
if services.ValidateFilename(name) == nil {
t.Fatalf("accepted %q", name)
}
}
if err := services.ValidateFilename("Фотография 1.png"); err != nil {
t.Fatal(err)
}
}
func TestAttachmentMessageRequiresStringText(t *testing.T) {
f := newTestFixture(t)
user, _ := createTestUser(t, f.users, "alice", "Alice")
chat := createTestChat(t, f.chats, "Images", []string{user.ID})
id := uuid.NewString()
// Repository-level fixture: message validation does not fetch S3 bytes.
err := repositories.NewAttachmentStore(f.db).Create(context.Background(), repositories.Attachment{
ID: id, ChatID: chat.ID, OwnerID: user.ID, Filename: "photo.png", ObjectKey: "test/" + id,
ContentType: "image/png", SizeBytes: 1, SHA256: strings.Repeat("a", 64), CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC(),
})
if err != nil {
t.Fatal(err)
}
for _, body := range []string{`{"attachment_ids":["` + id + `"]}`, `{"text":null,"attachment_ids":["` + id + `"]}`} {
r := httptest.NewRequest(http.MethodPost, "/api/v1/chats/"+chat.ID+"/messages", strings.NewReader(body))
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Idempotency-Key", uuid.NewString())
authorizeTestRequest(t, f, r, user.ID)
w := httptest.NewRecorder()
f.router.ServeHTTP(w, r)
if w.Code != 400 {
t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
}
}
if len(listTestMessages(t, f.messages, chat.ID)) != 0 {
t.Fatal("invalid request saved a message")
}
}
+2 -1
View File
@@ -3,6 +3,7 @@ package tests
import (
"context"
"errors"
"reflect"
"sync"
"testing"
@@ -44,7 +45,7 @@ func TestIdempotencyConcurrentStoresAndScopes(t *testing.T) {
for message := range results {
if original.ID == "" {
original = message
} else if message != original {
} else if !reflect.DeepEqual(message, original) {
t.Fatalf("replay changed the message: %v != %v", message, original)
}
}
+7
View File
@@ -85,6 +85,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/000004_attachments.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)
+63 -8
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState, type FormEvent } from "react";
import { api, ApiError, type Chat, type Session, type User } from "./api";
import { api, ApiError, type Attachment, type Chat, type Session, type User } from "./api";
import AttachmentImage from "./AttachmentImage";
import Pagination from "./Pagination";
import { useCursorPage } from "./useCursorPage";
@@ -111,6 +112,8 @@ function AuthForm({ onSuccess }: { onSuccess: (session: Session) => void }) {
);
}
type UploadDraft = { localId: string; file: File; status: "uploading" | "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);
@@ -119,7 +122,9 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog
const [drafts, setDrafts] = useState<Record<string, string>>({});
const [creating, setCreating] = useState(false);
const [sending, setSending] = useState(false);
const pendingMessages = useRef<Record<string, { text: string; key: string }>>({});
const 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) => {
@@ -144,19 +149,55 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog
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 });
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 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();
if (!text) return;
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?.text === text ? previous : { text, key: crypto.randomUUID() };
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);
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); }
@@ -189,7 +230,7 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog
<div className="list-toolbar"><span>{chats.items.length} на странице</span><button className="quiet" disabled={chats.busy} onClick={chats.refresh}>Обновить</button></div>
<div className="chat-list" aria-busy={chats.busy}>
{chats.busy ? <p className="empty-note">Загрузка…</p> : chats.failed ? <p className="empty-note">Не удалось загрузить чаты</p> : !chats.items.length && <p className="empty-note">Нет чатов</p>}
{chats.items.map((chat) => <button key={chat.id} className={`chat-item ${chatId === chat.id ? "selected" : ""}`} aria-pressed={chatId === chat.id} disabled={sending} onClick={() => setSelectedChat(chat)}><span className="chat-avatar">{chat.title.slice(0, 1).toUpperCase()}</span><span className="chat-copy"><strong>{chat.title}</strong><small>{chat.member_ids.length} участн.</small></span></button>)}
{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>
@@ -199,10 +240,24 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog
<header className="conversation-header"><div><h2>{selectedChat.title}</h2><details className="members"><summary>{selectedChat.member_ids.length} участн.</summary>{selectedChat.member_ids.map((id) => <code key={id}>{id}{id === user.id ? " · вы" : ""}</code>)}</details></div><button className="quiet" disabled={messages.busy || sending} onClick={messages.reload}>Обновить</button></header>
<div className="messages" aria-busy={messages.busy}>
{messages.busy ? <p className="empty-note">Загрузка…</p> : messages.failed ? <p className="empty-note">Не удалось загрузить сообщения</p> : !messages.items.length && <p className="empty-note">Нет сообщений</p>}
{messages.items.map((message) => <article key={message.id} className={`message ${message.sender_id === user.id ? "own" : ""}`}><div className="message-meta"><strong title={message.sender_id}>{message.sender_id === user.id ? "Вы" : message.sender_id.slice(0, 8)}</strong><time dateTime={message.created_at}>{dateText(message.created_at)}</time></div><p>{message.text}</p></article>)}
{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}><textarea aria-label="Сообщение" value={drafts[chatId] || ""} onChange={(event) => setDrafts({ ...drafts, [chatId]: event.target.value })} rows={2} maxLength={4000} required placeholder="Сообщение…" /><button className="primary" disabled={sending || messages.busy || !(drafts[chatId] || "").trim()}>{sending ? "Отправка…" : "Отправить"}</button></form>
<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>
+35
View File
@@ -0,0 +1,35 @@
import { useEffect, useState } from "react";
import { api } from "./api";
export default function AttachmentImage({ id, token, onError }: {
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>;
}
+23 -2
View File
@@ -12,11 +12,18 @@ export interface Chat {
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;
}
export interface Message {
id: string;
chat_id: string;
sender_id: string;
text: string;
attachment_ids: string[];
created_at: string;
}
@@ -118,10 +125,24 @@ export const api = {
headers: bearer(token),
});
},
sendMessage: (token: string, chatId: string, text: string, idempotencyKey: string) =>
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 }),
body: JSON.stringify({ text, attachment_ids: attachmentIds }),
}),
};
+115 -103
View File
@@ -1,103 +1,115 @@
@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;
}
* { 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; } }
@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;
}
* { 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; } }
+13 -4
View File
@@ -6,21 +6,30 @@ require (
github.com/golang-migrate/migrate/v4 v4.17.1
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.5.5
github.com/minio/minio-go/v7 v7.0.76
github.com/redis/go-redis/v9 v9.17.3
golang.org/x/crypto v0.22.0
golang.org/x/crypto v0.26.0
)
require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-ini/ini v1.67.0 // indirect
github.com/goccy/go-json v0.10.3 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/rs/xid v1.6.0 // indirect
go.uber.org/atomic v1.7.0 // indirect
golang.org/x/sync v0.5.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/net v0.28.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/text v0.17.0 // indirect
)
+34 -16
View File
@@ -23,6 +23,12 @@ github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKoh
github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-migrate/migrate/v4 v4.17.1 h1:4zQ6iqL6t6AiItphxJctQb3cFqWiSpMnX7wLTPnnYO4=
@@ -44,8 +50,17 @@ github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM=
github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.0.76 h1:9nxHH2XDai61cT/EFhyIw/wW4vJfpPNvl7lSFpRt+Ng=
github.com/minio/minio-go/v7 v7.0.76/go.mod h1:AVM3IUN6WwKzmwBxVdjzhH8xq+f57JSbbvzqvUzR6eg=
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
@@ -60,27 +75,30 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.17.3 h1:fN29NdNrE17KttK5Ndf20buqfDZwGNgoUr9qjl1DQx4=
github.com/redis/go-redis/v9 v9.17.3/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/mod v0.11.0 h1:bUO06HqtnRcc/7l71XBe4WcqTZ+3AH1J59zWDDwLKgU=
golang.org/x/mod v0.11.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.10.0 h1:tvDr/iQoUqNdohiYm0LmmKcBk+q86lb9EprIUFhHHGg=
golang.org/x/tools v0.10.0/go.mod h1:UJwyiVBsOA2uwvK/e5OY3GTpDUJriEd+/YlqAwLPmyM=
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=