Добавить вложения: S3, метаданные в PostgreSQL и очистка незавершённых загрузок

This commit is contained in:
2026-10-30 23:10:44 +03:00
parent ec540a1a72
commit d812d8f8d8
75 changed files with 5968 additions and 16 deletions
+7
View File
@@ -0,0 +1,7 @@
FROM haproxy:3.2.26-alpine
# конфигурация внутри образа: версия балансировщика и его настройки меняются только сборкой
COPY haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg
COPY errors/ /usr/local/etc/haproxy/errors/
RUN ["haproxy", "-c", "-f", "/usr/local/etc/haproxy/haproxy.cfg"]
+8
View File
@@ -0,0 +1,8 @@
HTTP/1.1 400 Bad Request
Content-Type: application/json
Content-Length: 119
Cache-Control: no-cache
Connection: close
X-Request-Id: lb-400
{"error": {"code": "invalid_request", "message": "Некорректный HTTP-запрос", "request_id": "lb-400"}}
+8
View File
@@ -0,0 +1,8 @@
HTTP/1.1 408 Request Timeout
Content-Type: application/json
Content-Length: 124
Cache-Control: no-cache
Connection: close
X-Request-Id: lb-408
{"error": {"code": "invalid_request", "message": "Запрос не получен вовремя", "request_id": "lb-408"}}
+8
View File
@@ -0,0 +1,8 @@
HTTP/1.1 414 URI Too Long
Content-Type: application/json
Content-Length: 132
Cache-Control: no-cache
Connection: close
X-Request-Id: lb-414
{"error": {"code": "invalid_request", "message": "Слишком длинный адрес запроса", "request_id": "lb-414"}}
+8
View File
@@ -0,0 +1,8 @@
HTTP/1.1 431 Request Header Fields Too Large
Content-Type: application/json
Content-Length: 140
Cache-Control: no-cache
Connection: close
X-Request-Id: lb-431
{"error": {"code": "invalid_request", "message": "Слишком большие заголовки запроса", "request_id": "lb-431"}}
+71
View File
@@ -0,0 +1,71 @@
global
log stdout format raw local0 info
maxconn 2000
defaults
mode http
log global
# в лог не попадают query string и заголовки: только путь, код, тайминги и выбранный сервер
log-format "%ci %HM %HPO status=%ST server=%s retries=%rc Tq=%TR Tw=%Tw Tc=%Tc Tr=%Tr Ta=%Ta"
# новое соединение с API на каждый запрос: остановленная реплика сразу видна как отказ соединения,
# а такой запрос до приложения не дошёл, поэтому его безопасно отправить на другую
option http-server-close
retries 2
retry-on conn-failure
option redispatch 1
timeout connect 1s
timeout http-request 10s
timeout queue 3s
# больше самого долгого ответа API: очередь на запись 10 с + S3 7 с + база и Redis по 1-2 с
timeout server 20s
timeout client 30s
timeout http-keep-alive 30s
timeout check 1s
# запрос, который не удалось разобрать: своего id у него ещё нет, поэтому ответы готовые, в формате контракта
errorfile 400 /usr/local/etc/haproxy/errors/400.http
errorfile 408 /usr/local/etc/haproxy/errors/408.http
errorfile 414 /usr/local/etc/haproxy/errors/414.http
errorfile 431 /usr/local/etc/haproxy/errors/431.http
resolvers docker
nameserver dns 127.0.0.11:53
accepted_payload_size 8192
# DNS Docker убирает остановленные контейнеры и добавляет новые, список реплик обновляется сам
timeout resolve 1s
timeout retry 1s
hold valid 2s
hold obsolete 0s
hold nx 2s
frontend api_in
bind *:8080
unique-id-format %[uuid(4)]
# грубый предел до API: файл 10 MiB проходит, точный лимит считает приложение
http-request deny deny_status 413 if { req.hdr_val(content-length) gt 11534336 }
default_backend api
# ответы самого балансировщика в формате ошибок контракта
http-error status 413 content-type application/json lf-string '{"error":{"code":"payload_too_large","message":"Слишком большое тело запроса","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 500 content-type application/json lf-string '{"error":{"code":"internal_error","message":"Внутренняя ошибка сервера","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
backend api
balance roundrobin
# без sticky session: любой запрос может уйти на любую реплику
option httpchk GET /health/ready
http-check expect status 200
# проверка раз в секунду, две неудачи подряд исключают реплику, две удачи возвращают
default-server check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
# до 6 реплик; адреса приходят из DNS по имени сервиса
server-template api 1-6 api:8080
# только внутри контейнера lb, порт не опубликован
frontend internal
bind *:8404
monitor-uri /lb-health
stats enable
stats uri /stats
stats refresh 0
no log
+5
View File
@@ -0,0 +1,5 @@
FROM chrislusf/seaweedfs:4.50
COPY start.sh /usr/local/bin/start-s3.sh
ENTRYPOINT ["/usr/local/bin/start-s3.sh"]
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
# Собирает конфигурацию ключей из секретов и запускает SeaweedFS. Анонимного доступа нет:
# запрос без подписи одного из этих ключей отклоняется, поэтому bucket приватный.
set -eu
secret() { cat "/run/secrets/$1"; }
bucket=${S3_BUCKET:-messenger-attachments}
umask 077
cat > /tmp/s3.json <<JSON
{
"identities": [
{
"name": "admin",
"credentials": [{"accessKey": "$(secret s3_admin_access_key_id)", "secretKey": "$(secret s3_admin_secret_access_key)"}],
"actions": ["Admin"]
},
{
"name": "api",
"credentials": [{"accessKey": "$(secret s3_access_key_id)", "secretKey": "$(secret s3_secret_access_key)"}],
"actions": ["Read:$bucket", "Write:$bucket"]
},
{
"name": "janitor",
"credentials": [{"accessKey": "$(secret s3_janitor_access_key_id)", "secretKey": "$(secret s3_janitor_secret_access_key)"}],
"actions": ["List:$bucket", "Write:$bucket"]
}
]
}
JSON
chown seaweed:seaweed /tmp/s3.json
exec /entrypoint.sh server -dir=/data -ip=s3 -ip.bind=0.0.0.0 \
-master.volumeSizeLimitMB=256 -volume.max=100 \
-s3 -s3.port=9000 -s3.config=/tmp/s3.json