Добавить вложения: S3-хранилище SeaweedFS, загрузку и скачивание через API, сверщик PostgreSQL и S3
This commit is contained in:
@@ -18,3 +18,15 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
tests
|
||||
student-tests
|
||||
contracts
|
||||
scripts
|
||||
examples
|
||||
*.md
|
||||
Makefile
|
||||
lab.json
|
||||
requirements-dev.txt
|
||||
Dockerfile*
|
||||
.dockerignore
|
||||
.gitignore
|
||||
|
||||
+25
-5
@@ -3,18 +3,38 @@
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
APP_SHUTDOWN_TIMEOUT=5
|
||||
APP_DRAIN_SECONDS=3
|
||||
# Host ports of the load balancer (change to 8090/8405 to run next to another lab stack).
|
||||
LB_PORT=8080
|
||||
STATS_PORT=8404
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
# Credentials are generated locally by: python scripts/init_secrets.py
|
||||
# File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
# Sessions: PostgreSQL is the source of truth, Valkey is a read-through cache.
|
||||
CACHE_URL=redis://valkey:6379/0
|
||||
SESSION_CACHE_TTL_SECONDS=60
|
||||
REVOCATION_SYNC_SECONDS=1
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
S3_ENDPOINT=http://s3:9000
|
||||
PASSWORD_HASH_CONCURRENCY=4
|
||||
DB_POOL_MIN=1
|
||||
DB_POOL_MAX=10
|
||||
DB_POOL_TIMEOUT_SECONDS=2
|
||||
DB_STATEMENT_TIMEOUT_MS=3000
|
||||
DB_REQUEST_TIMEOUT_SECONDS=4
|
||||
# S3 (SeaweedFS). API reads its own limited keys from secret files.
|
||||
S3_ENDPOINT=http://s3:8333
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
S3_TIMEOUT_SECONDS=15
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
UPLOAD_MEMORY_BYTES=1048576
|
||||
UPLOAD_CONCURRENCY=4
|
||||
# Periodic reconciler service: cleans orphans and stale uploads older than the grace period.
|
||||
RECONCILE_INTERVAL_SECONDS=600
|
||||
RECONCILE_GRACE_SECONDS=900
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
*.sh text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
FROM python:3.12.15-slim-trixie@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PIP_NO_CACHE_DIR=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
||||
PIP_ROOT_USER_ACTION=ignore
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
COPY migrations/ ./migrations/
|
||||
COPY src/ ./src/
|
||||
|
||||
RUN useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin app
|
||||
USER app
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=60s --start-interval=1s --retries=3 \
|
||||
CMD ["python", "-c", "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:%s/health/ready' % os.environ.get('APP_PORT', '8080'), timeout=2)"]
|
||||
|
||||
CMD ["python", "src/main.py"]
|
||||
@@ -4,7 +4,7 @@ CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
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 student-test
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -18,6 +18,9 @@ validate:
|
||||
test:
|
||||
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
student-test:
|
||||
BASE_URL="$(BASE_URL)" $(PYTHON) -m unittest discover -s student-tests -v
|
||||
|
||||
load:
|
||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
name: grigoriev-lab4
|
||||
|
||||
x-app-env: &app-env
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 8080
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
APP_SHUTDOWN_TIMEOUT: ${APP_SHUTDOWN_TIMEOUT:-5}
|
||||
APP_DRAIN_SECONDS: ${APP_DRAIN_SECONDS:-3}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
SESSION_CACHE_TTL_SECONDS: ${SESSION_CACHE_TTL_SECONDS:-60}
|
||||
REVOCATION_SYNC_SECONDS: ${REVOCATION_SYNC_SECONDS:-1}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-4}
|
||||
DB_POOL_MIN: ${DB_POOL_MIN:-1}
|
||||
DB_POOL_MAX: ${DB_POOL_MAX:-10}
|
||||
DB_POOL_TIMEOUT_SECONDS: ${DB_POOL_TIMEOUT_SECONDS:-2}
|
||||
DB_STATEMENT_TIMEOUT_MS: ${DB_STATEMENT_TIMEOUT_MS:-3000}
|
||||
DB_REQUEST_TIMEOUT_SECONDS: ${DB_REQUEST_TIMEOUT_SECONDS:-4}
|
||||
MALLOC_ARENA_MAX: "2"
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL: ${CACHE_URL:-redis://valkey:6379/0}
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-15}
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
UPLOAD_MEMORY_BYTES: ${UPLOAD_MEMORY_BYTES:-1048576}
|
||||
UPLOAD_CONCURRENCY: ${UPLOAD_CONCURRENCY:-4}
|
||||
FAULTS: ${FAULTS:-}
|
||||
|
||||
x-dns-opt: &dns-opt
|
||||
- timeout:1
|
||||
- attempts:1
|
||||
|
||||
services:
|
||||
lb:
|
||||
image: haproxy:3.0.30-alpine@sha256:d2b3567d836f3b7d174edb6d6f611ed5308e7966e53a9cd9a597e0415a298efd
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
ports:
|
||||
- "127.0.0.1:${LB_PORT:-8080}:8080"
|
||||
- "127.0.0.1:${STATS_PORT:-8404}:8404"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/lb/health"]
|
||||
interval: 5s
|
||||
timeout: 2s
|
||||
retries: 6
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.50", memory: 128M}
|
||||
networks: [frontend, backend]
|
||||
restart: unless-stopped
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: mtusi-messenger:lab4
|
||||
environment:
|
||||
<<: *app-env
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
secrets:
|
||||
- database_url
|
||||
- {source: s3_api_access_key_id, target: s3_access_key_id}
|
||||
- {source: s3_api_secret_access_key, target: s3_secret_access_key}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
valkey:
|
||||
condition: service_started
|
||||
dns_opt: *dns-opt
|
||||
stop_grace_period: 15s
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits: {cpus: "0.50", memory: 320M}
|
||||
networks: [backend]
|
||||
restart: unless-stopped
|
||||
|
||||
migrate:
|
||||
build: .
|
||||
image: mtusi-messenger:lab4
|
||||
command: ["python", "src/migrate.py"]
|
||||
environment: *app-env
|
||||
secrets: [database_url]
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.50", memory: 128M}
|
||||
networks: [backend]
|
||||
restart: "no"
|
||||
|
||||
s3:
|
||||
image: chrislusf/seaweedfs:4.48@sha256:4e61d15fd35994cb1e43e1e553dff106794841fd9a99ade2fc8c8bfce4d7872d
|
||||
command: ["server", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=127.0.0.1",
|
||||
"-s3", "-s3.port=8333", "-s3.ip.bind=0.0.0.0", "-s3.iam=false",
|
||||
"-s3.config=/run/secrets/s3_config.json",
|
||||
"-s3.concurrentUploadLimitMB=64", "-filer.concurrentUploadLimitMB=64",
|
||||
"-s3.cacheCapacityMB=16", "-s3.readerCacheSizeMB=32",
|
||||
"-master.volumeSizeLimitMB=256", "-volume.max=40", "-master.telemetry=false"]
|
||||
environment:
|
||||
GOMEMLIMIT: 300MiB
|
||||
secrets: [s3_config.json]
|
||||
volumes:
|
||||
- s3data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8333/healthz"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 10s
|
||||
stop_grace_period: 15s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.00", memory: 512M}
|
||||
networks: [backend]
|
||||
restart: unless-stopped
|
||||
|
||||
s3-init:
|
||||
build: .
|
||||
image: mtusi-messenger:lab4
|
||||
command: ["python", "src/s3_bootstrap.py"]
|
||||
environment:
|
||||
<<: *app-env
|
||||
S3_ADMIN_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access_key_id
|
||||
S3_ADMIN_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret_access_key
|
||||
secrets: [database_url, s3_admin_access_key_id, s3_admin_secret_access_key]
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.50", memory: 128M}
|
||||
networks: [backend]
|
||||
restart: "no"
|
||||
|
||||
reconcile:
|
||||
build: .
|
||||
image: mtusi-messenger:lab4
|
||||
profiles: [tools]
|
||||
entrypoint: ["python", "src/reconcile.py"]
|
||||
environment:
|
||||
<<: *app-env
|
||||
S3_RECONCILER_ACCESS_KEY_ID_FILE: /run/secrets/s3_reconciler_access_key_id
|
||||
S3_RECONCILER_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_reconciler_secret_access_key
|
||||
secrets: [database_url, s3_reconciler_access_key_id, s3_reconciler_secret_access_key]
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.50", memory: 256M}
|
||||
networks: [backend]
|
||||
|
||||
reconciler:
|
||||
build: .
|
||||
image: mtusi-messenger:lab4
|
||||
command: ["python", "src/reconcile.py", "--apply",
|
||||
"--interval", "${RECONCILE_INTERVAL_SECONDS:-600}", "--grace-seconds", "${RECONCILE_GRACE_SECONDS:-900}"]
|
||||
environment:
|
||||
<<: *app-env
|
||||
S3_RECONCILER_ACCESS_KEY_ID_FILE: /run/secrets/s3_reconciler_access_key_id
|
||||
S3_RECONCILER_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_reconciler_secret_access_key
|
||||
RECONCILE_INTERVAL_SECONDS: ${RECONCILE_INTERVAL_SECONDS:-600}
|
||||
secrets: [database_url, s3_reconciler_access_key_id, s3_reconciler_secret_access_key]
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
healthcheck:
|
||||
# жив цикл: файл-пульс обновлялся не позже интервала + 2 мин назад
|
||||
test: ["CMD", "python", "-c", "import os, sys, time; sys.exit(time.time() - os.path.getmtime('/tmp/reconciler.alive') > float(os.environ['RECONCILE_INTERVAL_SECONDS']) + 120)"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 60s
|
||||
start_interval: 1s
|
||||
stop_grace_period: 5s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.25", memory: 192M}
|
||||
networks: [backend]
|
||||
restart: unless-stopped
|
||||
|
||||
postgres:
|
||||
image: postgres:17.11-alpine@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
command: ["postgres", "-c", "track_io_timing=on"]
|
||||
secrets: [postgres_password]
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 10s
|
||||
stop_grace_period: 30s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.00", memory: 384M}
|
||||
networks: [backend]
|
||||
restart: unless-stopped
|
||||
|
||||
valkey:
|
||||
image: valkey/valkey:8.1.11-alpine@sha256:2602ace2be6569bc2bbb06f873776516ab9089821525be34f4305c67eb9db02a
|
||||
command: ["valkey-server", "--save", "", "--appendonly", "no",
|
||||
"--maxmemory", "64mb", "--maxmemory-policy", "volatile-ttl"]
|
||||
healthcheck:
|
||||
test: ["CMD", "valkey-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.25", memory: 96M}
|
||||
networks: [backend]
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
s3data:
|
||||
|
||||
networks:
|
||||
frontend:
|
||||
backend:
|
||||
internal: true
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
s3_config.json:
|
||||
file: ./secrets/s3_config.json
|
||||
s3_admin_access_key_id:
|
||||
file: ./secrets/s3_admin_access_key_id
|
||||
s3_admin_secret_access_key:
|
||||
file: ./secrets/s3_admin_secret_access_key
|
||||
s3_api_access_key_id:
|
||||
file: ./secrets/s3_api_access_key_id
|
||||
s3_api_secret_access_key:
|
||||
file: ./secrets/s3_api_secret_access_key
|
||||
s3_reconciler_access_key_id:
|
||||
file: ./secrets/s3_reconciler_access_key_id
|
||||
s3_reconciler_secret_access_key:
|
||||
file: ./secrets/s3_reconciler_secret_access_key
|
||||
@@ -0,0 +1,53 @@
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
maxconn 2000
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
option http-server-close
|
||||
option forwardfor
|
||||
option redispatch
|
||||
retries 2
|
||||
retry-on conn-failure
|
||||
timeout connect 1s
|
||||
timeout client 30s
|
||||
timeout server 60s
|
||||
timeout check 1s
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 2
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 2s
|
||||
hold obsolete 2s
|
||||
hold nx 2s
|
||||
accepted_payload_size 8192
|
||||
|
||||
frontend messenger
|
||||
bind :8080
|
||||
monitor-uri /lb/health
|
||||
use_backend api_live if { nbsrv(api) lt 1 }
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
default-server check inter 1s fall 2 rise 2 resolvers docker init-addr none
|
||||
server-template api 1-4 api:8080
|
||||
|
||||
backend api_live
|
||||
balance roundrobin
|
||||
option httpchk GET /health/live
|
||||
http-check expect status 200
|
||||
default-server check inter 1s fall 2 rise 2 resolvers docker init-addr none
|
||||
server-template live 1-4 api:8080
|
||||
|
||||
listen stats
|
||||
bind :8404
|
||||
stats enable
|
||||
stats uri /
|
||||
stats refresh 2s
|
||||
@@ -0,0 +1,46 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_by uuid NOT NULL REFERENCES users (id),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position smallint NOT NULL CHECK (position >= 1),
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
UNIQUE (chat_id, position)
|
||||
);
|
||||
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_user_idx ON sessions (user_id);
|
||||
CREATE INDEX sessions_expires_idx ON sessions (expires_at);
|
||||
@@ -0,0 +1,14 @@
|
||||
ALTER TABLE users
|
||||
DROP CONSTRAINT users_display_name_check,
|
||||
ALTER COLUMN display_name TYPE bytea USING convert_to(display_name, 'UTF8'),
|
||||
ADD CONSTRAINT users_display_name_check CHECK (octet_length(display_name) BETWEEN 1 AND 400);
|
||||
|
||||
ALTER TABLE chats
|
||||
DROP CONSTRAINT chats_title_check,
|
||||
ALTER COLUMN title TYPE bytea USING convert_to(title, 'UTF8'),
|
||||
ADD CONSTRAINT chats_title_check CHECK (octet_length(title) BETWEEN 1 AND 400);
|
||||
|
||||
ALTER TABLE messages
|
||||
DROP CONSTRAINT messages_text_check,
|
||||
ALTER COLUMN text TYPE bytea USING convert_to(text, 'UTF8'),
|
||||
ADD CONSTRAINT messages_text_check CHECK (octet_length(text) BETWEEN 1 AND 16000);
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE session_revocations (
|
||||
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX session_revocations_expires_idx ON session_revocations (expires_at);
|
||||
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE idempotency_keys (
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
scope text NOT NULL,
|
||||
key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
request_hash bytea NOT NULL CHECK (octet_length(request_hash) = 32),
|
||||
message_id uuid REFERENCES messages (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, scope, key)
|
||||
);
|
||||
|
||||
CREATE INDEX idempotency_keys_created_idx ON idempotency_keys (created_at);
|
||||
@@ -0,0 +1,30 @@
|
||||
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 CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
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 bytea NOT NULL CHECK (octet_length(sha256) = 32),
|
||||
object_key text NOT NULL UNIQUE,
|
||||
status text NOT NULL CHECK (status IN ('uploading', 'ready')),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
|
||||
CREATE INDEX attachments_chat_idx ON attachments (chat_id);
|
||||
CREATE INDEX attachments_status_created_idx ON attachments (status, created_at);
|
||||
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages (id),
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id),
|
||||
position smallint NOT NULL CHECK (position >= 1),
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
UNIQUE (message_id, position)
|
||||
);
|
||||
|
||||
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
|
||||
|
||||
ALTER TABLE messages
|
||||
DROP CONSTRAINT messages_text_check,
|
||||
ADD CONSTRAINT messages_text_check CHECK (octet_length(text) <= 16000);
|
||||
@@ -0,0 +1,27 @@
|
||||
annotated-types==0.8.0
|
||||
anyio==4.15.1
|
||||
argon2-cffi==25.1.0
|
||||
argon2-cffi-bindings==26.1.0
|
||||
boto3==1.44.1
|
||||
botocore==1.44.1
|
||||
cffi==2.1.1
|
||||
click==8.5.0
|
||||
fastapi==0.115.6
|
||||
h11==0.16.0
|
||||
idna==3.20
|
||||
jmespath==1.1.0
|
||||
pillow==13.0.0
|
||||
psycopg==3.3.6
|
||||
psycopg-binary==3.3.6
|
||||
psycopg-pool==3.3.3
|
||||
pycparser==3.12
|
||||
pydantic==2.10.4
|
||||
pydantic_core==2.27.2
|
||||
python-dateutil==2.9.0.post0
|
||||
redis==8.1.0
|
||||
s3transfer==0.19.3
|
||||
six==1.17.0
|
||||
starlette==0.41.3
|
||||
typing_extensions==4.16.0
|
||||
urllib3==2.8.0
|
||||
uvicorn==0.34.0
|
||||
@@ -0,0 +1,38 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = ROOT / 'secrets'
|
||||
|
||||
|
||||
def write(name, value):
|
||||
path = SECRETS / name
|
||||
if path.exists():
|
||||
print('keep existing secrets/%s' % name)
|
||||
return path.read_text(encoding='utf-8').strip()
|
||||
path.write_text(value + '\n', encoding='utf-8')
|
||||
os.chmod(path, 0o644)
|
||||
print('created secrets/%s' % name)
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
SECRETS.mkdir(exist_ok=True)
|
||||
password = write('postgres_password', secrets.token_hex(24))
|
||||
write('database_url', 'postgresql://messenger:%s@postgres:5432/messenger' % password)
|
||||
bucket = 'messenger-attachments'
|
||||
rights = {'admin': ['Admin', 'Read', 'List', 'Tagging', 'Write'],
|
||||
'api': ['Read:' + bucket, 'Write:' + bucket],
|
||||
'reconciler': ['Read:' + bucket, 'List:' + bucket, 'Write:' + bucket]}
|
||||
identities = []
|
||||
for role, actions in rights.items():
|
||||
key = write('s3_%s_access_key_id' % role, role + '-' + secrets.token_hex(8))
|
||||
secret = write('s3_%s_secret_access_key' % role, secrets.token_hex(24))
|
||||
identities.append({'name': role, 'credentials': [{'accessKey': key, 'secretKey': secret}], 'actions': actions})
|
||||
write('s3_config.json', json.dumps({'identities': identities}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose stop api || exit /b 1
|
||||
docker compose restart postgres valkey s3 || exit /b 1
|
||||
docker compose up -d --no-build --no-recreate --wait postgres valkey s3 || exit /b 1
|
||||
docker compose start api || exit /b 1
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose stop api
|
||||
docker compose restart postgres valkey s3
|
||||
docker compose up -d --no-build --no-recreate --wait postgres valkey s3
|
||||
docker compose start api
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Поочерёдная замена API-реплик без остановки сервиса.
|
||||
|
||||
python scripts/rolling_update.py # пересобрать образ и заменить реплики по одной
|
||||
python scripts/rolling_update.py --no-build # заменить на текущий образ
|
||||
|
||||
1. Один раз применяет миграции (отдельный контейнер migrate; совместимые, только добавляющие изменения).
|
||||
2. Для каждой старой реплики: поднимает одну новую (--scale +1, --no-recreate), ждёт, пока LB начнёт
|
||||
отправлять на неё трафик, затем штатно останавливает старую (SIGTERM → вывод из ротации → завершение)
|
||||
и удаляет её контейнер. Число реплик в ротации не опускается ниже исходного.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://127.0.0.1:8080').rstrip('/')
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(['docker', 'compose', *args], cwd=ROOT, check=True, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def running_api():
|
||||
return compose('ps', '-q', 'api').split()
|
||||
|
||||
|
||||
def instance_of_next_response():
|
||||
try:
|
||||
with urllib.request.urlopen(BASE_URL + '/health/ready', timeout=2) as response:
|
||||
return response.headers.get('X-Instance-Id')
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def wait_in_rotation(container, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if instance_of_next_response() == container[:12]:
|
||||
return
|
||||
time.sleep(0.1)
|
||||
raise SystemExit('new replica %s did not enter LB rotation' % container[:12])
|
||||
|
||||
|
||||
def image_of(container):
|
||||
return subprocess.run(['docker', 'inspect', '-f', '{{.Image}}', container], capture_output=True, text=True).stdout.strip()[7:19]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--no-build', action='store_true')
|
||||
args = parser.parse_args()
|
||||
old = running_api()
|
||||
print('old replicas:', ', '.join('%s(image %s)' % (c[:12], image_of(c)) for c in old))
|
||||
if not args.no_build:
|
||||
compose('build', 'api')
|
||||
compose('run', '--rm', '--no-deps', 'migrate')
|
||||
print('migrations applied once')
|
||||
for container in old:
|
||||
before = set(running_api())
|
||||
compose('up', '-d', '--no-deps', '--no-recreate', '--scale', 'api=%d' % (len(before) + 1), 'api')
|
||||
new = (set(running_api()) - before).pop()
|
||||
started = time.monotonic()
|
||||
wait_in_rotation(new)
|
||||
print('+ %s (image %s) in rotation after %.1fs' % (new[:12], image_of(new), time.monotonic() - started))
|
||||
started = time.monotonic()
|
||||
subprocess.run(['docker', 'stop', '-t', '15', container], check=True, capture_output=True)
|
||||
subprocess.run(['docker', 'rm', container], check=True, capture_output=True)
|
||||
print('- %s stopped and removed after %.1fs' % (container[:12], time.monotonic() - started))
|
||||
print('new replicas:', ', '.join('%s(image %s)' % (c[:12], image_of(c)) for c in running_api()))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,11 @@
|
||||
@echo off
|
||||
if "%TARGET_INSTANCE_ID%"=="" exit /b 2
|
||||
cd /d "%~dp0.."
|
||||
for /f %%i in ('docker compose ps -q api') do (
|
||||
echo %%i| findstr /b /i "%TARGET_INSTANCE_ID%" >nul && (
|
||||
docker stop -t 10 %%i >nul
|
||||
exit /b 0
|
||||
)
|
||||
)
|
||||
echo no running api replica matches TARGET_INSTANCE_ID 1>&2
|
||||
exit /b 1
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
cd "$(dirname "$0")/.."
|
||||
for id in $(docker compose ps -q api); do
|
||||
case "$id" in
|
||||
"$TARGET_INSTANCE_ID"*)
|
||||
docker stop -t 10 "$id" >/dev/null
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
done
|
||||
echo "no running api replica matches TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
from contextlib import asynccontextmanager
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import socket
|
||||
import time
|
||||
import tempfile
|
||||
import threading
|
||||
from typing import Annotated, Literal, Optional
|
||||
import uuid
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, Query, Request, Response
|
||||
from fastapi.responses import StreamingResponse
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
import psycopg
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
import auth
|
||||
from cache import cache
|
||||
from config import settings
|
||||
from db import connection, pool, request_deadline, restart_budget
|
||||
from errors import ApiError, error_response
|
||||
import images
|
||||
from models import CreateChat, CreateMessage, CreateUser
|
||||
import s3
|
||||
import store
|
||||
|
||||
log = logging.getLogger('messenger')
|
||||
|
||||
Limit = Annotated[int, Query(ge=1, le=100)]
|
||||
Cursor = Annotated[Optional[str], Query(min_length=1)]
|
||||
|
||||
INSTANCE_ID = socket.gethostname()
|
||||
IDEMPOTENCY_KEY = re.compile(r'^[A-Za-z0-9._:-]{1,128}$')
|
||||
|
||||
PUBLIC = {('POST', '/api/v1/users'), ('POST', '/api/v1/auth/sessions')}
|
||||
|
||||
state = {'ready': False}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
pool.open(wait=False)
|
||||
log.info('instance %s, session cache: %s', INSTANCE_ID, 'valkey' if cache.client else 'disabled')
|
||||
state['ready'] = True
|
||||
log.info('application started')
|
||||
yield
|
||||
state['ready'] = False
|
||||
log.info('application stopping')
|
||||
pool.close(timeout=2)
|
||||
|
||||
|
||||
app = FastAPI(title='MTUSI Messenger lab4', lifespan=lifespan)
|
||||
|
||||
|
||||
@app.middleware('http')
|
||||
async def request_context(request: Request, call_next):
|
||||
request.state.request_id = uuid.uuid4().hex
|
||||
request_deadline.set({'deadline': None})
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
log.exception('unhandled error request_id=%s', request.state.request_id)
|
||||
response = error_response(request, 500, 'Внутренняя ошибка сервера')
|
||||
response.headers['X-Request-Id'] = request.state.request_id
|
||||
response.headers['X-Instance-Id'] = INSTANCE_ID
|
||||
log.info('%s %s -> %d %.1fms request_id=%s', request.method, request.url.path,
|
||||
response.status_code, (time.perf_counter() - started) * 1000, request.state.request_id)
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def handle_api_error(request: Request, exc: ApiError):
|
||||
return error_response(request, exc.status, exc.message, exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def handle_http_error(request: Request, exc: StarletteHTTPException):
|
||||
messages = {404: 'Ресурс не найден', 405: 'Метод не поддерживается'}
|
||||
return error_response(request, exc.status_code, messages.get(exc.status_code, 'Ошибка запроса'))
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def handle_validation_error(request: Request, exc: RequestValidationError):
|
||||
if request.url.path.startswith('/api/v1/') and (request.method, request.url.path) not in PUBLIC:
|
||||
try:
|
||||
await run_in_threadpool(auth.authenticate, request.headers.get('authorization'))
|
||||
except ApiError as error:
|
||||
return error_response(request, error.status, error.message, error.headers)
|
||||
except (psycopg.OperationalError, psycopg.InterfaceError):
|
||||
return error_response(request, 503, 'Хранилище временно недоступно')
|
||||
errors = exc.errors()
|
||||
where = '.'.join(str(part) for part in errors[0]['loc']) if errors else 'request'
|
||||
return error_response(request, 400, 'Некорректный запрос: ' + where)
|
||||
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
@app.exception_handler(psycopg.InterfaceError)
|
||||
async def handle_database_unavailable(request: Request, exc: psycopg.Error):
|
||||
log.warning('database unavailable: %s request_id=%s', type(exc).__name__, request.state.request_id)
|
||||
return error_response(request, 503, 'Хранилище временно недоступно')
|
||||
|
||||
|
||||
@app.get('/health/live')
|
||||
async def liveness():
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
@app.get('/health/ready')
|
||||
def readiness():
|
||||
if not state['ready']:
|
||||
raise ApiError(503, 'Сервис не готов')
|
||||
with connection(limit=1) as conn:
|
||||
conn.execute('SELECT 1')
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def current_session(authorization: Annotated[Optional[str], Header()] = None):
|
||||
return auth.authenticate(authorization)
|
||||
|
||||
|
||||
def current_user(session: Annotated[dict, Depends(current_session)]):
|
||||
return session['user']
|
||||
|
||||
|
||||
@app.post('/api/v1/users', status_code=201)
|
||||
def register_user(body: CreateUser):
|
||||
return store.create_user(body.username, body.display_name, auth.hash_password(body.password))
|
||||
|
||||
|
||||
@app.post('/api/v1/auth/sessions', status_code=201)
|
||||
def create_session(request: Request, authorization: Annotated[Optional[str], Header()] = None):
|
||||
if request.headers.get('content-length', '0') != '0' or 'transfer-encoding' in request.headers:
|
||||
raise ApiError(400, 'Вход принимает только заголовок Authorization: Basic, без тела')
|
||||
return auth.login(authorization)
|
||||
|
||||
|
||||
@app.delete('/api/v1/auth/sessions/current', status_code=204)
|
||||
def delete_session(session: Annotated[dict, Depends(current_session)]):
|
||||
auth.logout(session)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.get('/api/v1/users/me')
|
||||
def get_me(user: Annotated[dict, Depends(current_user)]):
|
||||
return user
|
||||
|
||||
|
||||
@app.post('/api/v1/chats', status_code=201)
|
||||
def create_chat(body: CreateChat, user: Annotated[dict, Depends(current_user)]):
|
||||
return store.create_chat(user['id'], body.title, body.member_ids)
|
||||
|
||||
|
||||
@app.get('/api/v1/chats')
|
||||
def list_chats(user: Annotated[dict, Depends(current_user)], limit: Limit = 50, cursor: Cursor = None):
|
||||
return store.list_chats(user['id'], cursor, limit)
|
||||
|
||||
|
||||
@app.get('/api/v1/chats/{chat_id}')
|
||||
def get_chat(chat_id: uuid.UUID, user: Annotated[dict, Depends(current_user)]):
|
||||
return store.get_chat(str(chat_id), user['id'])
|
||||
|
||||
|
||||
@app.post('/api/v1/chats/{chat_id}/messages', status_code=201)
|
||||
def create_message(chat_id: uuid.UUID, body: CreateMessage, user: Annotated[dict, Depends(current_user)],
|
||||
idempotency_key: Annotated[Optional[str], Header()] = None):
|
||||
if idempotency_key is None or not IDEMPOTENCY_KEY.match(idempotency_key):
|
||||
raise ApiError(400, 'Нужен заголовок Idempotency-Key: [A-Za-z0-9._:-]{1,128}')
|
||||
canonical = json.dumps({'text': body.text, 'attachment_ids': body.attachment_ids}, ensure_ascii=False, sort_keys=True)
|
||||
return store.create_message(str(chat_id), user['id'], body.text, body.attachment_ids, idempotency_key,
|
||||
hashlib.sha256(canonical.encode('utf-8')).digest(), settings.idempotency_ttl)
|
||||
|
||||
|
||||
@app.get('/api/v1/chats/{chat_id}/messages')
|
||||
def list_messages(chat_id: uuid.UUID, user: Annotated[dict, Depends(current_user)],
|
||||
limit: Limit = 50, cursor: Cursor = None):
|
||||
return store.list_messages(str(chat_id), user['id'], cursor, limit)
|
||||
|
||||
|
||||
uploads = threading.BoundedSemaphore(settings.upload_concurrency)
|
||||
|
||||
|
||||
def save_attachment(chat_id, owner_id, filename, content_type, spool, size, sha256):
|
||||
if not uploads.acquire(timeout=settings.upload_queue_seconds):
|
||||
raise ApiError(503, 'Слишком много одновременных загрузок, повторите позже')
|
||||
try:
|
||||
return store_upload(chat_id, owner_id, filename, content_type, spool, size, sha256)
|
||||
finally:
|
||||
uploads.release()
|
||||
|
||||
|
||||
def store_upload(chat_id, owner_id, filename, content_type, spool, size, sha256):
|
||||
images.inspect(spool, content_type)
|
||||
attachment_id = str(uuid.uuid4())
|
||||
object_key = 'attachments/' + attachment_id
|
||||
restart_budget()
|
||||
store.start_attachment(attachment_id, chat_id, owner_id, filename, content_type, size, sha256, object_key)
|
||||
restart_budget()
|
||||
try:
|
||||
s3.put(object_key, spool, size, content_type)
|
||||
except ApiError:
|
||||
try:
|
||||
store.forget_attachment(attachment_id)
|
||||
except psycopg.Error:
|
||||
pass
|
||||
raise
|
||||
if 'after_s3_put' in settings.faults and filename.startswith('fault-'):
|
||||
raise RuntimeError('fault injection: process failed after S3 PUT, before COMMIT of ready')
|
||||
restart_budget()
|
||||
return store.finish_attachment(attachment_id)
|
||||
|
||||
|
||||
@app.post('/api/v1/chats/{chat_id}/attachments', status_code=201)
|
||||
async def upload_attachment(chat_id: uuid.UUID, request: Request, user: Annotated[dict, Depends(current_user)],
|
||||
filename: Optional[str] = None):
|
||||
images.check_filename(filename)
|
||||
content_type = images.check_content_type(request.headers.get('content-type'))
|
||||
await run_in_threadpool(store.check_member, str(chat_id), user['id'])
|
||||
declared = request.headers.get('content-length', '')
|
||||
if declared.isdigit() and int(declared) > settings.max_upload_bytes:
|
||||
raise ApiError(413, 'Файл больше %d байт' % settings.max_upload_bytes)
|
||||
spool = tempfile.SpooledTemporaryFile(max_size=settings.upload_memory_bytes)
|
||||
try:
|
||||
size, digest = 0, hashlib.sha256()
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > settings.max_upload_bytes:
|
||||
raise ApiError(413, 'Файл больше %d байт' % settings.max_upload_bytes)
|
||||
digest.update(chunk)
|
||||
spool.write(chunk)
|
||||
if size == 0:
|
||||
raise ApiError(415, 'Пустое тело вместо изображения')
|
||||
return await run_in_threadpool(save_attachment, str(chat_id), user['id'], filename, content_type,
|
||||
spool, size, digest.digest())
|
||||
finally:
|
||||
spool.close()
|
||||
|
||||
|
||||
@app.get('/api/v1/attachments/{attachment_id}')
|
||||
def get_attachment(attachment_id: uuid.UUID, user: Annotated[dict, Depends(current_user)]):
|
||||
return store.attachment_out(store.get_attachment(str(attachment_id), user['id']))
|
||||
|
||||
|
||||
@app.get('/api/v1/attachments/{attachment_id}/content')
|
||||
def download_attachment(attachment_id: uuid.UUID, user: Annotated[dict, Depends(current_user)],
|
||||
variant: Literal['original'] = 'original'):
|
||||
row = store.get_attachment(str(attachment_id), user['id'])
|
||||
return StreamingResponse(s3.open_stream(row['object_key']), media_type=row['content_type'],
|
||||
headers={'Content-Length': str(row['size_bytes'])})
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
import psycopg
|
||||
|
||||
from cache import REVOKED, cache
|
||||
from config import settings
|
||||
from db import iso
|
||||
from errors import BASIC_CHALLENGE, BEARER_CHALLENGE, unauthorized
|
||||
import store
|
||||
|
||||
REVOCATION_MARGIN_SECONDS = 5
|
||||
|
||||
USERNAME = re.compile(r'^[a-z0-9_]{3,32}$')
|
||||
|
||||
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
hashing = threading.BoundedSemaphore(settings.password_hash_concurrency)
|
||||
DUMMY_HASH = hasher.hash('dummy-password-for-equal-timing')
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
with hashing:
|
||||
return hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash, password):
|
||||
try:
|
||||
with hashing:
|
||||
return hasher.verify(password_hash, password)
|
||||
except (VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
return hashlib.sha256(token.encode('ascii')).digest()
|
||||
|
||||
|
||||
def parse_credentials(header, scheme):
|
||||
name, _, value = (header or '').strip().partition(' ')
|
||||
value = value.strip()
|
||||
if name.lower() != scheme or not value or ' ' in value:
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def parse_basic(header):
|
||||
value = parse_credentials(header, 'basic')
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
decoded = base64.b64decode(value, validate=True).decode('utf-8')
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
return None
|
||||
username, separator, password = decoded.partition(':')
|
||||
if not separator or not USERNAME.match(username) or not 12 <= len(password) <= 128:
|
||||
return None
|
||||
return username, password
|
||||
|
||||
|
||||
def login(header):
|
||||
credentials = parse_basic(header)
|
||||
row = store.find_credentials(credentials[0]) if credentials else None
|
||||
if row is None:
|
||||
verify_password(DUMMY_HASH, credentials[1] if credentials else 'x' * 12)
|
||||
raise unauthorized(BASIC_CHALLENGE, 'Неверное имя пользователя или пароль')
|
||||
if not verify_password(row['password_hash'], credentials[1]):
|
||||
raise unauthorized(BASIC_CHALLENGE, 'Неверное имя пользователя или пароль')
|
||||
token = secrets.token_urlsafe(32)
|
||||
digest = token_hash(token)
|
||||
expires_at = store.create_session(row['id'], digest, settings.session_ttl)
|
||||
user = store.user_out(row)
|
||||
cache.put(digest, user, expires_at)
|
||||
return {'token': token, 'token_type': 'Bearer', 'expires_at': iso(expires_at), 'user': user}
|
||||
|
||||
|
||||
def authenticate(header):
|
||||
token = parse_credentials(header, 'bearer')
|
||||
if token is None or not token.isascii():
|
||||
raise unauthorized(BEARER_CHALLENGE)
|
||||
digest = token_hash(token)
|
||||
if cache.client is not None and not cache.trusted():
|
||||
sync_revocations()
|
||||
user = cache.get(digest)
|
||||
if user == REVOKED:
|
||||
raise unauthorized(BEARER_CHALLENGE)
|
||||
if user is None:
|
||||
row = store.session_user(digest)
|
||||
if row is None:
|
||||
raise unauthorized(BEARER_CHALLENGE)
|
||||
user = store.user_out(row)
|
||||
cache.put(digest, user, row['expires_at'])
|
||||
return {'user': user, 'token_hash': digest}
|
||||
|
||||
|
||||
def sync_revocations():
|
||||
errors_before = cache.errors
|
||||
pending = store.pending_revocations()
|
||||
if not cache.revoke_all(pending):
|
||||
return
|
||||
if pending:
|
||||
try:
|
||||
store.clear_revocations(pending)
|
||||
except psycopg.Error:
|
||||
pass
|
||||
cache.mark_synced(errors_before)
|
||||
|
||||
|
||||
def logout(session):
|
||||
store.revoke_session(session['token_hash'], cache.max_ttl + REVOCATION_MARGIN_SECONDS)
|
||||
if cache.revoke(session['token_hash']):
|
||||
try:
|
||||
store.clear_revocations([session['token_hash']])
|
||||
except psycopg.Error:
|
||||
pass
|
||||
@@ -0,0 +1,89 @@
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
|
||||
import redis
|
||||
|
||||
from config import settings
|
||||
|
||||
log = logging.getLogger('messenger.cache')
|
||||
|
||||
BYPASS_SECONDS = 5
|
||||
REVOKED = 'revoked'
|
||||
FAILED = object()
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, url, max_ttl):
|
||||
self.client = redis.Redis.from_url(url, socket_timeout=0.2, socket_connect_timeout=0.2,
|
||||
decode_responses=True) if url else None
|
||||
self.max_ttl = max_ttl
|
||||
self.bypass_until = 0.0
|
||||
self.lock = threading.Lock()
|
||||
self.errors = 0
|
||||
self.synced = False
|
||||
self.synced_at = 0.0
|
||||
|
||||
def _run(self, action, force=False):
|
||||
if self.client is None:
|
||||
return None
|
||||
if not force and time.monotonic() < self.bypass_until:
|
||||
return FAILED
|
||||
try:
|
||||
return action(self.client)
|
||||
except redis.RedisError as error:
|
||||
log.warning('session cache unavailable (%s), using PostgreSQL for %ds', type(error).__name__, BYPASS_SECONDS)
|
||||
self.bypass_until = time.monotonic() + BYPASS_SECONDS
|
||||
with self.lock:
|
||||
self.errors += 1
|
||||
self.synced = False
|
||||
return FAILED
|
||||
|
||||
@staticmethod
|
||||
def key(token_hash):
|
||||
return 'session:' + token_hash.hex()
|
||||
|
||||
def mark_synced(self, errors_before):
|
||||
with self.lock:
|
||||
if self.errors == errors_before:
|
||||
self.synced = True
|
||||
self.synced_at = time.monotonic()
|
||||
|
||||
def trusted(self):
|
||||
return self.synced and time.monotonic() - self.synced_at < settings.revocation_sync_seconds
|
||||
|
||||
def get(self, token_hash):
|
||||
if not self.trusted():
|
||||
return None
|
||||
raw = self._run(lambda c: c.get(self.key(token_hash)))
|
||||
if raw is FAILED or not raw or raw == REVOKED:
|
||||
return REVOKED if raw == REVOKED else None
|
||||
entry = json.loads(raw)
|
||||
if entry['expires_at'] <= time.time():
|
||||
return None
|
||||
return entry['user']
|
||||
|
||||
def put(self, token_hash, user, expires_at: datetime):
|
||||
remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds())
|
||||
ttl = min(self.max_ttl, remaining)
|
||||
if ttl <= 0:
|
||||
return
|
||||
value = json.dumps({'user': user, 'expires_at': expires_at.timestamp()}, ensure_ascii=False)
|
||||
self._run(lambda c: c.set(self.key(token_hash), value, ex=ttl, nx=True))
|
||||
|
||||
def revoke(self, token_hash):
|
||||
return self._run(lambda c: c.set(self.key(token_hash), REVOKED, ex=self.max_ttl), force=True) is not FAILED
|
||||
|
||||
def revoke_all(self, token_hashes):
|
||||
def write(client):
|
||||
with client.pipeline(transaction=False) as pipe:
|
||||
for token_hash in token_hashes:
|
||||
pipe.set(self.key(token_hash), REVOKED, ex=self.max_ttl)
|
||||
pipe.execute()
|
||||
return True
|
||||
return not token_hashes or self._run(write) is not FAILED
|
||||
|
||||
|
||||
cache = SessionCache(settings.cache_url, settings.session_cache_ttl)
|
||||
@@ -0,0 +1,54 @@
|
||||
import os
|
||||
|
||||
|
||||
def setting(name, default=None):
|
||||
path = os.environ.get(name + '_FILE')
|
||||
if path:
|
||||
with open(path, encoding='utf-8') as file:
|
||||
return file.read().strip()
|
||||
return os.environ.get(name, default)
|
||||
|
||||
|
||||
def positive_int(name, default):
|
||||
value = int(os.environ.get(name, default))
|
||||
if value <= 0:
|
||||
raise SystemExit('%s must be a positive integer' % name)
|
||||
return value
|
||||
|
||||
|
||||
class Settings:
|
||||
def __init__(self):
|
||||
self.host = os.environ.get('APP_HOST', '0.0.0.0')
|
||||
self.port = positive_int('APP_PORT', '8080')
|
||||
self.env = os.environ.get('APP_ENV', 'lab')
|
||||
self.shutdown_timeout = positive_int('APP_SHUTDOWN_TIMEOUT', '5')
|
||||
self.database_url = setting('DATABASE_URL')
|
||||
self.cache_url = setting('CACHE_URL') or None
|
||||
self.session_ttl = positive_int('SESSION_TTL_SECONDS', '3600')
|
||||
self.session_cache_ttl = positive_int('SESSION_CACHE_TTL_SECONDS', '60')
|
||||
self.db_pool_min = positive_int('DB_POOL_MIN', '1')
|
||||
self.db_pool_max = positive_int('DB_POOL_MAX', '10')
|
||||
self.db_pool_timeout = float(os.environ.get('DB_POOL_TIMEOUT_SECONDS', '2'))
|
||||
self.db_statement_timeout_ms = positive_int('DB_STATEMENT_TIMEOUT_MS', '3000')
|
||||
self.db_request_timeout = float(os.environ.get('DB_REQUEST_TIMEOUT_SECONDS', '4'))
|
||||
self.drain_seconds = float(os.environ.get('APP_DRAIN_SECONDS', '3'))
|
||||
self.idempotency_ttl = positive_int('IDEMPOTENCY_TTL_SECONDS', '86400')
|
||||
self.revocation_sync_seconds = float(os.environ.get('REVOCATION_SYNC_SECONDS', '1'))
|
||||
self.password_hash_concurrency = positive_int('PASSWORD_HASH_CONCURRENCY', '4')
|
||||
self.s3_endpoint = os.environ.get('S3_ENDPOINT', 'http://s3:8333')
|
||||
self.s3_region = os.environ.get('S3_REGION', 'us-east-1')
|
||||
self.s3_bucket = os.environ.get('S3_BUCKET', 'messenger-attachments')
|
||||
self.s3_access_key = setting('S3_ACCESS_KEY_ID')
|
||||
self.s3_secret_key = setting('S3_SECRET_ACCESS_KEY')
|
||||
self.s3_timeout = float(os.environ.get('S3_TIMEOUT_SECONDS', '15'))
|
||||
self.max_upload_bytes = positive_int('MAX_UPLOAD_BYTES', '10485760')
|
||||
self.max_image_pixels = positive_int('MAX_IMAGE_PIXELS', '40000000')
|
||||
self.upload_memory_bytes = positive_int('UPLOAD_MEMORY_BYTES', '1048576')
|
||||
self.upload_concurrency = positive_int('UPLOAD_CONCURRENCY', '4')
|
||||
self.upload_queue_seconds = float(os.environ.get('UPLOAD_QUEUE_SECONDS', '30'))
|
||||
self.faults = set(filter(None, os.environ.get('FAULTS', '').split(',')))
|
||||
if not self.database_url:
|
||||
raise SystemExit('DATABASE_URL or DATABASE_URL_FILE is required')
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,133 @@
|
||||
from contextlib import contextmanager
|
||||
import contextvars
|
||||
from datetime import timezone
|
||||
import itertools
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from config import settings
|
||||
|
||||
log = logging.getLogger('messenger.db')
|
||||
|
||||
request_deadline = contextvars.ContextVar('request_deadline', default=None)
|
||||
|
||||
CHECK_SECONDS = 1
|
||||
|
||||
|
||||
def abort(conn):
|
||||
try:
|
||||
sock = socket.socket(fileno=os.dup(conn.fileno()))
|
||||
except (OSError, psycopg.Error):
|
||||
return
|
||||
try:
|
||||
sock.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
sock.close()
|
||||
|
||||
|
||||
class Watchdog:
|
||||
def __init__(self):
|
||||
self.cond = threading.Condition()
|
||||
self.armed = {}
|
||||
self.ids = itertools.count()
|
||||
threading.Thread(target=self.loop, name='db-watchdog', daemon=True).start()
|
||||
|
||||
@contextmanager
|
||||
def guard(self, conn, seconds):
|
||||
key = next(self.ids)
|
||||
with self.cond:
|
||||
self.armed[key] = (time.monotonic() + seconds, conn)
|
||||
self.cond.notify()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
with self.cond:
|
||||
self.armed.pop(key, None)
|
||||
|
||||
def loop(self):
|
||||
with self.cond:
|
||||
while True:
|
||||
now = time.monotonic()
|
||||
for key, (deadline, conn) in list(self.armed.items()):
|
||||
if deadline <= now:
|
||||
del self.armed[key]
|
||||
log.warning('database did not answer in time, aborting connection')
|
||||
abort(conn)
|
||||
wake = min((deadline for deadline, _ in self.armed.values()), default=now + 60)
|
||||
self.cond.wait(max(wake - now, 0.01))
|
||||
|
||||
|
||||
watchdog = Watchdog()
|
||||
|
||||
|
||||
def check(conn):
|
||||
with watchdog.guard(conn, CHECK_SECONDS):
|
||||
ConnectionPool.check_connection(conn)
|
||||
|
||||
|
||||
pool = ConnectionPool(
|
||||
settings.database_url,
|
||||
min_size=settings.db_pool_min,
|
||||
max_size=settings.db_pool_max,
|
||||
timeout=settings.db_pool_timeout,
|
||||
check=check,
|
||||
open=False,
|
||||
name='messenger',
|
||||
kwargs={
|
||||
'connect_timeout': 3,
|
||||
'row_factory': dict_row,
|
||||
'options': '-c timezone=UTC -c statement_timeout=%d' % settings.db_statement_timeout_ms,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def restart_budget():
|
||||
budget = request_deadline.get()
|
||||
if budget is not None:
|
||||
budget['deadline'] = None
|
||||
|
||||
|
||||
def remaining(limit=None):
|
||||
budget = request_deadline.get()
|
||||
if budget is None:
|
||||
left = settings.db_request_timeout
|
||||
else:
|
||||
if budget['deadline'] is None:
|
||||
budget['deadline'] = time.monotonic() + settings.db_request_timeout
|
||||
left = budget['deadline'] - time.monotonic()
|
||||
if limit is not None:
|
||||
left = min(left, limit)
|
||||
if left <= 0:
|
||||
raise psycopg.OperationalError('request deadline exceeded')
|
||||
return left
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection(limit=None):
|
||||
conn = pool.getconn(timeout=min(settings.db_pool_timeout, remaining(limit)))
|
||||
try:
|
||||
with watchdog.guard(conn, remaining(limit)):
|
||||
try:
|
||||
yield conn
|
||||
except BaseException:
|
||||
try:
|
||||
conn.rollback()
|
||||
except psycopg.Error:
|
||||
pass
|
||||
raise
|
||||
conn.commit()
|
||||
finally:
|
||||
pool.putconn(conn)
|
||||
|
||||
|
||||
def iso(value):
|
||||
return value.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
|
||||
@@ -0,0 +1,37 @@
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
CODES = {
|
||||
400: 'invalid_request',
|
||||
401: 'unauthorized',
|
||||
404: 'not_found',
|
||||
409: 'conflict',
|
||||
413: 'payload_too_large',
|
||||
415: 'unsupported_media_type',
|
||||
429: 'rate_limited',
|
||||
500: 'internal_error',
|
||||
503: 'unavailable',
|
||||
}
|
||||
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status, message, headers=None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.message = message
|
||||
self.headers = headers
|
||||
|
||||
|
||||
def unauthorized(challenge, message='Нужна действительная сессия'):
|
||||
return ApiError(401, message, {'WWW-Authenticate': challenge})
|
||||
|
||||
|
||||
def error_response(request: Request, status, message, headers=None):
|
||||
request_id = getattr(request.state, 'request_id', '-')
|
||||
body = {'error': {'code': CODES.get(status, 'invalid_request'), 'message': message, 'request_id': request_id}}
|
||||
if status == 401 and not headers:
|
||||
headers = {'WWW-Authenticate': BEARER_CHALLENGE}
|
||||
return JSONResponse(body, status_code=status, headers=headers)
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from config import settings
|
||||
from errors import ApiError
|
||||
|
||||
SIGNATURES = {'image/png': b'\x89PNG\r\n\x1a\n', 'image/jpeg': b'\xff\xd8\xff'}
|
||||
FORMATS = {'image/png': 'PNG', 'image/jpeg': 'JPEG'}
|
||||
FORBIDDEN_FILENAME = set('/\\\x7f') | {chr(code) for code in range(32)} | {chr(code) for code in range(0x80, 0xa0)}
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = settings.max_image_pixels
|
||||
|
||||
|
||||
def check_filename(filename):
|
||||
if filename is None or not 1 <= len(filename) <= 255 or not filename.strip() \
|
||||
or any(char in FORBIDDEN_FILENAME for char in filename):
|
||||
raise ApiError(400, 'Некорректный filename: 1–255 символов без /, \\ и управляющих символов')
|
||||
try:
|
||||
filename.encode('utf-8')
|
||||
except UnicodeEncodeError:
|
||||
raise ApiError(400, 'Некорректный filename') from None
|
||||
|
||||
|
||||
def check_content_type(header):
|
||||
content_type = (header or '').split(';')[0].strip().lower()
|
||||
if content_type not in SIGNATURES:
|
||||
raise ApiError(415, 'Принимаются только сырые байты image/png или image/jpeg')
|
||||
return content_type
|
||||
|
||||
|
||||
CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
|
||||
ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
|
||||
|
||||
|
||||
def png_rows(ihdr):
|
||||
width, height, depth, color, _, _, interlace = struct.unpack('>IIBBBBB', ihdr)
|
||||
bits = depth * CHANNELS[color]
|
||||
if interlace:
|
||||
passes = [(-(-(width - x0) // dx), -(-(height - y0) // dy)) for x0, y0, dx, dy in ADAM7]
|
||||
else:
|
||||
passes = [(width, height)]
|
||||
return [((w * bits + 7) // 8 + 1, h) for w, h in passes if w > 0 and h > 0]
|
||||
|
||||
|
||||
class PixelData:
|
||||
def __init__(self, ihdr, piece):
|
||||
self.rows = png_rows(ihdr)
|
||||
self.expected = sum(length * count for length, count in self.rows)
|
||||
self.inflater = zlib.decompressobj()
|
||||
self.piece = piece
|
||||
self.total = 0
|
||||
self.segment = 0
|
||||
self.offset = 0
|
||||
|
||||
def feed(self, data):
|
||||
while data:
|
||||
if self.inflater.eof:
|
||||
return
|
||||
out = self.inflater.decompress(data, self.piece)
|
||||
data = self.inflater.unconsumed_tail
|
||||
self.check(out)
|
||||
|
||||
def check(self, out):
|
||||
self.total += len(out)
|
||||
if self.total > self.expected:
|
||||
raise ValueError('PNG pixel data is longer than IHDR allows')
|
||||
while out:
|
||||
length, count = self.rows[self.segment]
|
||||
take = min(len(out), length * count - self.offset)
|
||||
part, out = out[:take], out[take:]
|
||||
filters = part[(-self.offset) % length::length]
|
||||
if filters and max(filters) > 4:
|
||||
raise ValueError('PNG row has an invalid filter type')
|
||||
self.offset += take
|
||||
if self.offset == length * count:
|
||||
self.segment, self.offset = self.segment + 1, 0
|
||||
|
||||
def finish(self):
|
||||
if not self.inflater.eof or self.total != self.expected:
|
||||
raise ValueError('PNG pixel data is truncated')
|
||||
|
||||
|
||||
def verify_png(fileobj, piece=64 * 1024):
|
||||
"""Потоково: CRC каждого чанка и распаковка IDAT кусками по piece байт без хранения пикселей."""
|
||||
fileobj.seek(8)
|
||||
pixels = None
|
||||
while True:
|
||||
header = fileobj.read(8)
|
||||
if len(header) < 8:
|
||||
raise ValueError('PNG ended before IEND')
|
||||
length, kind = struct.unpack('>I4s', header)
|
||||
if pixels is None and kind != b'IHDR':
|
||||
raise ValueError('PNG must start with IHDR')
|
||||
crc = zlib.crc32(kind)
|
||||
left = length
|
||||
while left:
|
||||
data = fileobj.read(min(piece, left))
|
||||
if not data:
|
||||
raise ValueError('PNG chunk is truncated')
|
||||
crc = zlib.crc32(data, crc)
|
||||
left -= len(data)
|
||||
if kind == b'IHDR':
|
||||
pixels = PixelData(data, piece)
|
||||
elif kind == b'IDAT':
|
||||
pixels.feed(data)
|
||||
stored = fileobj.read(4)
|
||||
if len(stored) < 4 or struct.unpack('>I', stored)[0] != crc & 0xffffffff:
|
||||
raise ValueError('PNG chunk CRC mismatch')
|
||||
if kind == b'IEND':
|
||||
pixels.finish()
|
||||
return
|
||||
|
||||
|
||||
def inspect(fileobj, content_type):
|
||||
fileobj.seek(0)
|
||||
if not fileobj.read(8).startswith(SIGNATURES[content_type]):
|
||||
raise ApiError(415, 'Содержимое файла не соответствует ' + content_type)
|
||||
fileobj.seek(0)
|
||||
try:
|
||||
with Image.open(fileobj, formats=[FORMATS[content_type]]) as image:
|
||||
width, height = image.size
|
||||
if width * height > settings.max_image_pixels:
|
||||
raise ApiError(413, 'Изображение больше %d пикселей' % settings.max_image_pixels)
|
||||
if content_type == 'image/png':
|
||||
verify_png(fileobj)
|
||||
else:
|
||||
image.draft('L', (max(1, width // 8), max(1, height // 8)))
|
||||
image.load()
|
||||
except ApiError:
|
||||
raise
|
||||
except Image.DecompressionBombError:
|
||||
raise ApiError(413, 'Изображение больше %d пикселей' % settings.max_image_pixels) from None
|
||||
except Exception:
|
||||
raise ApiError(415, 'Файл повреждён или не является изображением ' + content_type) from None
|
||||
finally:
|
||||
fileobj.seek(0)
|
||||
return width, height
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import logging
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import uvicorn
|
||||
|
||||
from config import settings
|
||||
|
||||
|
||||
class DrainingServer(uvicorn.Server):
|
||||
def handle_exit(self, sig, frame):
|
||||
from app import state
|
||||
if not state['ready'] or settings.drain_seconds <= 0:
|
||||
return super().handle_exit(sig, frame)
|
||||
state['ready'] = False
|
||||
logging.getLogger('messenger').info('signal %s: readiness off, draining for %.1fs', sig, settings.drain_seconds)
|
||||
threading.Timer(settings.drain_seconds, super().handle_exit, (sig, frame)).start()
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
|
||||
format='%(asctime)s %(levelname)s %(name)s: %(message)s')
|
||||
logging.getLogger('messenger').info('config host=%s port=%d env=%s session_ttl=%ds session_cache_ttl=%ds',
|
||||
settings.host, settings.port, settings.env,
|
||||
settings.session_ttl, settings.session_cache_ttl)
|
||||
|
||||
from app import app
|
||||
config = uvicorn.Config(app, host=settings.host, port=settings.port, access_log=False, log_config=None,
|
||||
timeout_graceful_shutdown=settings.shutdown_timeout)
|
||||
DrainingServer(config).run()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,47 @@
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
import psycopg
|
||||
|
||||
from config import settings
|
||||
|
||||
MIGRATIONS = Path(__file__).resolve().parent.parent / 'migrations'
|
||||
LOCK_ID = 20260002
|
||||
|
||||
log = logging.getLogger('migrate')
|
||||
|
||||
|
||||
def connect(attempts=30):
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
return psycopg.connect(settings.database_url, autocommit=True, connect_timeout=3)
|
||||
except psycopg.OperationalError:
|
||||
if attempt == attempts:
|
||||
raise
|
||||
log.info('database is not ready, retry %d/%d', attempt, attempts)
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s %(name)s: %(message)s')
|
||||
with connect() as conn:
|
||||
conn.execute('SELECT pg_advisory_lock(%s)', (LOCK_ID,))
|
||||
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations ('
|
||||
'version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())')
|
||||
applied = {row[0] for row in conn.execute('SELECT version FROM schema_migrations')}
|
||||
for path in sorted(MIGRATIONS.glob('*.sql')):
|
||||
if path.stem in applied:
|
||||
log.info('skip %s: already applied', path.stem)
|
||||
continue
|
||||
with conn.transaction():
|
||||
conn.execute(path.read_text(encoding='utf-8'))
|
||||
conn.execute('INSERT INTO schema_migrations (version) VALUES (%s)', (path.stem,))
|
||||
log.info('applied %s', path.stem)
|
||||
conn.execute('SELECT pg_advisory_unlock(%s)', (LOCK_ID,))
|
||||
log.info('schema is up to date')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,62 @@
|
||||
import uuid
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid', strict=True)
|
||||
|
||||
|
||||
def not_blank(value):
|
||||
if not value.strip():
|
||||
raise ValueError('must not be blank')
|
||||
try:
|
||||
value.encode('utf-8')
|
||||
except UnicodeEncodeError:
|
||||
raise ValueError('must be valid Unicode') from None
|
||||
return value
|
||||
|
||||
|
||||
class CreateUser(StrictModel):
|
||||
username: str = Field(pattern=r'^[a-z0-9_]{3,32}$')
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator('display_name', 'password')
|
||||
@classmethod
|
||||
def not_blank_fields(cls, value):
|
||||
return not_blank(value)
|
||||
|
||||
|
||||
class CreateChat(StrictModel):
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator('title')
|
||||
@classmethod
|
||||
def title_not_blank(cls, value):
|
||||
return not_blank(value)
|
||||
|
||||
|
||||
class CreateMessage(StrictModel):
|
||||
text: str = Field(max_length=4000)
|
||||
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator('attachment_ids')
|
||||
@classmethod
|
||||
def valid_attachment_ids(cls, value):
|
||||
try:
|
||||
ids = [str(uuid.UUID(item)) for item in value]
|
||||
except ValueError:
|
||||
raise ValueError('attachment_ids must be UUIDs') from None
|
||||
if len(set(ids)) != len(ids):
|
||||
raise ValueError('attachment_ids must be unique')
|
||||
return ids
|
||||
|
||||
@model_validator(mode='after')
|
||||
def text_or_attachments(self):
|
||||
if not self.attachment_ids:
|
||||
not_blank(self.text)
|
||||
else:
|
||||
self.text.encode('utf-8')
|
||||
return self
|
||||
@@ -0,0 +1,31 @@
|
||||
import base64
|
||||
from datetime import datetime
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from errors import ApiError
|
||||
|
||||
|
||||
def encode_cursor(scope, item):
|
||||
raw = json.dumps({'s': scope, 't': item['created_at'], 'i': item['id']}, separators=(',', ':'))
|
||||
return base64.urlsafe_b64encode(raw.encode()).decode().rstrip('=')
|
||||
|
||||
|
||||
def decode_cursor(scope, cursor):
|
||||
try:
|
||||
padded = cursor + '=' * (-len(cursor) % 4)
|
||||
data = json.loads(base64.urlsafe_b64decode(padded.encode('ascii')))
|
||||
if data['s'] != scope or not isinstance(data['t'], str) or not isinstance(data['i'], str):
|
||||
raise ValueError
|
||||
created_at = datetime.fromisoformat(data['t'])
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError
|
||||
return created_at, uuid.UUID(data['i'])
|
||||
except (ValueError, TypeError, KeyError, AttributeError):
|
||||
raise ApiError(400, 'Некорректный cursor') from None
|
||||
|
||||
|
||||
def page(items, scope, limit):
|
||||
chunk = items[:limit]
|
||||
has_more = len(items) > limit
|
||||
return {'items': chunk, 'next_cursor': encode_cursor(scope, chunk[-1]) if has_more else None}
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Сверка PostgreSQL (метаданные вложений) и S3 (байты).
|
||||
|
||||
python src/reconcile.py # dry-run: только отчёт
|
||||
python src/reconcile.py --apply # исправить то, что безопасно исправлять
|
||||
python src/reconcile.py --grace-seconds 900 --report /tmp/report.json
|
||||
python src/reconcile.py --apply --interval 600 # периодически (сервис reconciler в compose)
|
||||
|
||||
Категории:
|
||||
ok — ready-строка и объект на месте (размер совпадает);
|
||||
orphan — объект без строки, старше grace → удалить объект;
|
||||
fresh_orphan — объект без строки, моложе grace → не трогать (загрузка может идти прямо сейчас);
|
||||
stale_upload — строка 'uploading' старше grace → удалить строку и объект (если он есть);
|
||||
fresh_upload — строка 'uploading' моложе grace → не трогать;
|
||||
missing — ready-строка без объекта → только отчёт (восстановить нечего, удалять метаданные нельзя);
|
||||
size_mismatch — ready-строка и объект разного размера → только отчёт.
|
||||
Сначала читается список объектов, потом таблица: объект появляется в S3 только после строки 'uploading',
|
||||
поэтому у любого увиденного объекта, загруженного API, строка уже есть или была удалена компенсацией.
|
||||
"""
|
||||
import argparse
|
||||
from datetime import timezone
|
||||
import json
|
||||
import logging
|
||||
import resource
|
||||
import signal
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from config import setting, settings
|
||||
from s3 import make_client
|
||||
|
||||
PREFIX = 'attachments/'
|
||||
HEARTBEAT = '/tmp/reconciler.alive' # обновляется после каждого прохода цикла; по нему healthcheck
|
||||
|
||||
log = logging.getLogger('reconcile')
|
||||
|
||||
|
||||
def list_objects(client):
|
||||
objects, pages = {}, 0
|
||||
for page in client.get_paginator('list_objects_v2').paginate(Bucket=settings.s3_bucket, Prefix=PREFIX):
|
||||
pages += 1
|
||||
for item in page.get('Contents', []):
|
||||
objects[item['Key']] = {'size': item['Size'], 'modified': item['LastModified'].astimezone(timezone.utc)}
|
||||
return objects, pages
|
||||
|
||||
|
||||
def classify(objects, rows, now, grace):
|
||||
found = {name: [] for name in ('ok', 'orphan', 'fresh_orphan', 'stale_upload', 'fresh_upload', 'missing',
|
||||
'size_mismatch')}
|
||||
by_key = {row['object_key']: row for row in rows}
|
||||
for key, info in objects.items():
|
||||
if key not in by_key:
|
||||
age = (now - info['modified']).total_seconds()
|
||||
found['orphan' if age > grace else 'fresh_orphan'].append({'object_key': key, 'age_s': round(age)})
|
||||
for row in rows:
|
||||
age = (now - row['created_at']).total_seconds()
|
||||
item = {'id': str(row['id']), 'object_key': row['object_key'], 'age_s': round(age),
|
||||
'referenced': row['referenced'], 'object_exists': row['object_key'] in objects}
|
||||
if row['status'] == 'uploading':
|
||||
found['stale_upload' if age > grace else 'fresh_upload'].append(item)
|
||||
elif row['object_key'] not in objects:
|
||||
found['missing'].append(item)
|
||||
elif objects[row['object_key']]['size'] != row['size_bytes']:
|
||||
found['size_mismatch'].append(item)
|
||||
else:
|
||||
found['ok'].append(item)
|
||||
return found
|
||||
|
||||
|
||||
def apply(found, client, db):
|
||||
done = {'orphan_objects_deleted': 0, 'stale_rows_deleted': 0, 'stale_objects_deleted': 0, 'skipped': 0}
|
||||
for item in found['orphan']:
|
||||
if db.execute('SELECT 1 FROM attachments WHERE object_key = %s', (item['object_key'],)).fetchone():
|
||||
done['skipped'] += 1
|
||||
continue
|
||||
client.delete_object(Bucket=settings.s3_bucket, Key=item['object_key'])
|
||||
done['orphan_objects_deleted'] += 1
|
||||
for item in found['stale_upload']:
|
||||
deleted = db.execute("DELETE FROM attachments WHERE id = %s AND status = 'uploading' "
|
||||
"AND NOT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = %s) RETURNING 1",
|
||||
(item['id'], item['id'])).fetchone()
|
||||
db.commit()
|
||||
if not deleted:
|
||||
done['skipped'] += 1
|
||||
continue
|
||||
done['stale_rows_deleted'] += 1
|
||||
if item['object_exists']:
|
||||
client.delete_object(Bucket=settings.s3_bucket, Key=item['object_key'])
|
||||
done['stale_objects_deleted'] += 1
|
||||
return done
|
||||
|
||||
|
||||
def run_once(client, args):
|
||||
started = time.monotonic()
|
||||
with psycopg.connect(settings.database_url, row_factory=dict_row, connect_timeout=5) as db:
|
||||
objects, pages = list_objects(client)
|
||||
listed = time.monotonic()
|
||||
now = db.execute('SELECT now() AS now').fetchone()['now'].astimezone(timezone.utc)
|
||||
rows = db.execute('SELECT a.id, a.object_key, a.status, a.size_bytes, a.created_at, '
|
||||
'EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id) AS referenced '
|
||||
'FROM attachments a').fetchall()
|
||||
db.commit()
|
||||
scanned = time.monotonic()
|
||||
found = classify(objects, rows, now, args.grace_seconds)
|
||||
done = apply(found, client, db) if args.apply else None
|
||||
report = {
|
||||
'mode': 'apply' if args.apply else 'dry-run', 'grace_seconds': args.grace_seconds,
|
||||
'objects_listed': len(objects), 'list_pages': pages, 'rows_scanned': len(rows),
|
||||
'counts': {name: len(items) for name, items in found.items()},
|
||||
'actions': done,
|
||||
'seconds': {'list_s3': round(listed - started, 3), 'scan_db': round(scanned - listed, 3),
|
||||
'total': round(time.monotonic() - started, 3)},
|
||||
'max_rss_mib': round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 1),
|
||||
'missing': found['missing'], 'size_mismatch': found['size_mismatch'],
|
||||
}
|
||||
if args.details:
|
||||
report['items'] = {name: items for name, items in found.items() if name != 'ok'}
|
||||
return report
|
||||
|
||||
|
||||
def run_forever(client, args):
|
||||
"""Периодический режим (сервис reconciler): прогон сразу и далее каждые --interval секунд."""
|
||||
stop = threading.Event()
|
||||
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||
log.info('periodic mode: every %.0fs, %s, grace %.0fs', args.interval,
|
||||
'apply' if args.apply else 'dry-run', args.grace_seconds)
|
||||
while not stop.is_set():
|
||||
try:
|
||||
report = run_once(client, args)
|
||||
log.info('run: objects %d, rows %d, counts %s, actions %s, %.2fs', report['objects_listed'],
|
||||
report['rows_scanned'], {k: v for k, v in report['counts'].items() if v},
|
||||
report['actions'], report['seconds']['total'])
|
||||
except Exception as error:
|
||||
log.warning('run failed, will retry next time: %s: %s', type(error).__name__, error)
|
||||
with open(HEARTBEAT, 'w') as file:
|
||||
file.write(str(time.time()))
|
||||
stop.wait(args.interval)
|
||||
log.info('stopped')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--apply', action='store_true')
|
||||
parser.add_argument('--grace-seconds', type=float, default=900)
|
||||
parser.add_argument('--interval', type=float, default=0, help='repeat every N seconds (0 = run once)')
|
||||
parser.add_argument('--report')
|
||||
parser.add_argument('--details', action='store_true', help='include every item in the report')
|
||||
args = parser.parse_args()
|
||||
logging.basicConfig(stream=sys.stderr, level=logging.INFO, format='%(asctime)s %(name)s: %(message)s')
|
||||
client = make_client(setting('S3_RECONCILER_ACCESS_KEY_ID'), setting('S3_RECONCILER_SECRET_ACCESS_KEY'), timeout=30)
|
||||
if args.interval > 0:
|
||||
run_forever(client, args)
|
||||
return
|
||||
text = json.dumps(run_once(client, args), ensure_ascii=False, indent=2, default=str)
|
||||
if args.report:
|
||||
with open(args.report, 'w', encoding='utf-8') as file:
|
||||
file.write(text)
|
||||
print(text)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,65 @@
|
||||
import logging
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from config import settings
|
||||
from errors import ApiError
|
||||
|
||||
log = logging.getLogger('messenger.s3')
|
||||
|
||||
CHUNK = 64 * 1024
|
||||
|
||||
|
||||
def make_client(access_key, secret_key, timeout=None):
|
||||
return boto3.client(
|
||||
's3', endpoint_url=settings.s3_endpoint, region_name=settings.s3_region,
|
||||
aws_access_key_id=access_key, aws_secret_access_key=secret_key,
|
||||
config=Config(signature_version='s3v4', s3={'addressing_style': 'path'},
|
||||
connect_timeout=timeout or settings.s3_timeout, read_timeout=timeout or settings.s3_timeout,
|
||||
retries={'max_attempts': 2, 'mode': 'standard'},
|
||||
request_checksum_calculation='when_required', response_checksum_validation='when_required'))
|
||||
|
||||
|
||||
client = make_client(settings.s3_access_key, settings.s3_secret_key) if settings.s3_access_key else None
|
||||
|
||||
|
||||
def unavailable(error):
|
||||
log.warning('object storage unavailable: %s', type(error).__name__)
|
||||
return ApiError(503, 'Хранилище файлов временно недоступно')
|
||||
|
||||
|
||||
def put(key, fileobj, size, content_type):
|
||||
try:
|
||||
client.put_object(Bucket=settings.s3_bucket, Key=key, Body=fileobj, ContentLength=size,
|
||||
ContentType=content_type)
|
||||
except (BotoCoreError, ClientError) as error:
|
||||
raise unavailable(error) from None
|
||||
|
||||
|
||||
def delete(key):
|
||||
try:
|
||||
client.delete_object(Bucket=settings.s3_bucket, Key=key)
|
||||
return True
|
||||
except (BotoCoreError, ClientError) as error:
|
||||
log.warning('could not delete object %s: %s', key, type(error).__name__)
|
||||
return False
|
||||
|
||||
|
||||
def open_stream(key):
|
||||
try:
|
||||
body = client.get_object(Bucket=settings.s3_bucket, Key=key)['Body']
|
||||
except ClientError as error:
|
||||
if error.response.get('Error', {}).get('Code') in ('NoSuchKey', '404'):
|
||||
log.error('object %s is missing for a ready attachment', key)
|
||||
raise unavailable(error) from None
|
||||
except BotoCoreError as error:
|
||||
raise unavailable(error) from None
|
||||
|
||||
def chunks():
|
||||
try:
|
||||
yield from body.iter_chunks(CHUNK)
|
||||
finally:
|
||||
body.close()
|
||||
return chunks()
|
||||
@@ -0,0 +1,55 @@
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from config import setting, settings
|
||||
from s3 import make_client
|
||||
|
||||
log = logging.getLogger('s3-bootstrap')
|
||||
|
||||
|
||||
def wait_for(client, attempts=30):
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
return client.list_buckets()
|
||||
except (BotoCoreError, ClientError) as error:
|
||||
if attempt == attempts:
|
||||
raise
|
||||
log.info('object storage is not ready (%s), retry %d/%d', type(error).__name__, attempt, attempts)
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def anonymous_status(path):
|
||||
try:
|
||||
urllib.request.urlopen(settings.s3_endpoint + path, timeout=5)
|
||||
return 200
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s %(name)s: %(message)s')
|
||||
admin = make_client(setting('S3_ADMIN_ACCESS_KEY_ID'), setting('S3_ADMIN_SECRET_ACCESS_KEY'))
|
||||
buckets = {bucket['Name'] for bucket in wait_for(admin).get('Buckets', [])}
|
||||
if settings.s3_bucket in buckets:
|
||||
log.info('bucket %s already exists, nothing to do', settings.s3_bucket)
|
||||
else:
|
||||
admin.create_bucket(Bucket=settings.s3_bucket)
|
||||
log.info('bucket %s created', settings.s3_bucket)
|
||||
started = time.monotonic()
|
||||
admin.put_object(Bucket=settings.s3_bucket, Key='bootstrap/warmup', Body=b'warmup')
|
||||
admin.delete_object(Bucket=settings.s3_bucket, Key='bootstrap/warmup')
|
||||
log.info('warm-up write done in %.1fs (storage volumes allocated before first upload)', time.monotonic() - started)
|
||||
for path in ('/' + settings.s3_bucket, '/' + settings.s3_bucket + '/probe'):
|
||||
status = anonymous_status(path)
|
||||
if status not in (401, 403):
|
||||
raise SystemExit('anonymous access to %s returned %d, bucket is not private' % (path, status))
|
||||
log.info('anonymous list/get denied: bucket %s is private', settings.s3_bucket)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
import uuid
|
||||
|
||||
from psycopg import errors
|
||||
|
||||
from db import connection, iso
|
||||
from errors import ApiError
|
||||
from pagination import decode_cursor, page
|
||||
|
||||
USER_COLUMNS = 'u.id, u.username, u.display_name, u.created_at'
|
||||
ATTACHMENT_IDS = ('ARRAY(SELECT ma.attachment_id FROM message_attachments ma '
|
||||
'WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids')
|
||||
MESSAGE_COLUMNS = 'm.id, m.chat_id, m.sender_id, m.text, m.created_at, ' + ATTACHMENT_IDS
|
||||
ATTACHMENT_COLUMNS = 'a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.object_key, a.status, a.created_at, a.updated_at'
|
||||
CHAT_SELECT = ('SELECT c.id, c.title, c.created_at, '
|
||||
'ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids '
|
||||
'FROM chats c ')
|
||||
|
||||
|
||||
def utf8(value):
|
||||
return value.encode('utf-8')
|
||||
|
||||
|
||||
def unicode(value):
|
||||
return bytes(value).decode('utf-8')
|
||||
|
||||
|
||||
def user_out(row):
|
||||
return {'id': str(row['id']), 'username': row['username'],
|
||||
'display_name': unicode(row['display_name']), 'created_at': iso(row['created_at'])}
|
||||
|
||||
|
||||
def chat_out(row):
|
||||
return {'id': str(row['id']), 'title': unicode(row['title']),
|
||||
'member_ids': [str(m) for m in row['member_ids']], 'created_at': iso(row['created_at'])}
|
||||
|
||||
|
||||
def message_out(row):
|
||||
return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'sender_id': str(row['sender_id']),
|
||||
'text': unicode(row['text']), 'created_at': iso(row['created_at']),
|
||||
'attachment_ids': [str(a) for a in row['attachment_ids']]}
|
||||
|
||||
|
||||
def attachment_out(row):
|
||||
return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'owner_id': str(row['owner_id']),
|
||||
'filename': row['filename'], 'content_type': row['content_type'], 'size_bytes': row['size_bytes'],
|
||||
'sha256': bytes(row['sha256']).hex(), 'status': row['status'], 'variants': [], 'error_code': None,
|
||||
'created_at': iso(row['created_at']), 'updated_at': iso(row['updated_at'])}
|
||||
|
||||
|
||||
def create_user(username, display_name, password_hash):
|
||||
try:
|
||||
with connection() as conn:
|
||||
row = conn.execute(
|
||||
'INSERT INTO users AS u (username, display_name, password_hash) VALUES (%s, %s, %s) '
|
||||
'RETURNING ' + USER_COLUMNS,
|
||||
(username, utf8(display_name), password_hash)).fetchone()
|
||||
except errors.UniqueViolation:
|
||||
raise ApiError(409, 'Имя пользователя уже занято') from None
|
||||
return user_out(row)
|
||||
|
||||
|
||||
def find_credentials(username):
|
||||
with connection() as conn:
|
||||
return conn.execute('SELECT ' + USER_COLUMNS + ', u.password_hash FROM users u WHERE u.username = %s',
|
||||
(username,)).fetchone()
|
||||
|
||||
|
||||
def create_session(user_id, token_hash, ttl_seconds):
|
||||
with connection() as conn:
|
||||
conn.execute('DELETE FROM sessions WHERE user_id = %s AND expires_at <= now()', (user_id,))
|
||||
return conn.execute(
|
||||
'INSERT INTO sessions (token_hash, user_id, expires_at) '
|
||||
'VALUES (%s, %s, now() + make_interval(secs => %s)) RETURNING expires_at',
|
||||
(token_hash, user_id, ttl_seconds)).fetchone()['expires_at']
|
||||
|
||||
|
||||
def session_user(token_hash):
|
||||
with connection() as conn:
|
||||
return conn.execute(
|
||||
'SELECT ' + USER_COLUMNS + ', s.expires_at FROM sessions s JOIN users u ON u.id = s.user_id '
|
||||
'WHERE s.token_hash = %s AND s.expires_at > now()',
|
||||
(token_hash,)).fetchone()
|
||||
|
||||
|
||||
def revoke_session(token_hash, keep_seconds):
|
||||
with connection() as conn:
|
||||
conn.execute('DELETE FROM sessions WHERE token_hash = %s', (token_hash,))
|
||||
conn.execute('INSERT INTO session_revocations (token_hash, expires_at) '
|
||||
'VALUES (%s, now() + make_interval(secs => %s)) '
|
||||
'ON CONFLICT (token_hash) DO UPDATE SET expires_at = EXCLUDED.expires_at',
|
||||
(token_hash, keep_seconds))
|
||||
|
||||
|
||||
def pending_revocations():
|
||||
with connection() as conn:
|
||||
conn.execute('DELETE FROM session_revocations WHERE expires_at <= now()')
|
||||
return [bytes(r['token_hash']) for r in conn.execute('SELECT token_hash FROM session_revocations').fetchall()]
|
||||
|
||||
|
||||
def clear_revocations(token_hashes):
|
||||
with connection() as conn:
|
||||
conn.execute('DELETE FROM session_revocations WHERE token_hash = ANY(%s)', (list(token_hashes),))
|
||||
|
||||
|
||||
def create_chat(creator_id, title, member_ids):
|
||||
try:
|
||||
members = [str(uuid.UUID(m)) for m in member_ids]
|
||||
except ValueError:
|
||||
raise ApiError(400, 'Неизвестный участник чата') from None
|
||||
if len(set(members)) != len(members):
|
||||
raise ApiError(400, 'Участники не должны повторяться')
|
||||
if creator_id not in members:
|
||||
raise ApiError(400, 'Создатель должен быть участником чата')
|
||||
try:
|
||||
with connection() as conn, conn.transaction():
|
||||
chat = conn.execute('INSERT INTO chats (title, created_by) VALUES (%s, %s) RETURNING id, title, created_at',
|
||||
(utf8(title), creator_id)).fetchone()
|
||||
conn.execute('INSERT INTO chat_members (chat_id, user_id, position) '
|
||||
'SELECT %s, member, position FROM unnest(%s::uuid[]) WITH ORDINALITY AS t(member, position)',
|
||||
(chat['id'], members))
|
||||
except errors.ForeignKeyViolation:
|
||||
raise ApiError(400, 'Неизвестный участник чата') from None
|
||||
return chat_out({**chat, 'member_ids': members})
|
||||
|
||||
|
||||
def get_chat(chat_id, user_id):
|
||||
with connection() as conn:
|
||||
row = conn.execute(CHAT_SELECT + 'JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s '
|
||||
'WHERE c.id = %s', (user_id, chat_id)).fetchone()
|
||||
if row is None:
|
||||
raise ApiError(404, 'Чат не найден')
|
||||
return chat_out(row)
|
||||
|
||||
|
||||
def list_chats(user_id, cursor, limit):
|
||||
scope = 'user:' + user_id
|
||||
sql = CHAT_SELECT + 'JOIN chat_members me ON me.chat_id = c.id WHERE me.user_id = %s '
|
||||
params = [user_id]
|
||||
if cursor:
|
||||
sql += 'AND (c.created_at, c.id) > (%s, %s) '
|
||||
params += decode_cursor(scope, cursor)
|
||||
sql += 'ORDER BY c.created_at, c.id LIMIT %s'
|
||||
with connection() as conn:
|
||||
rows = conn.execute(sql, params + [limit + 1]).fetchall()
|
||||
return page([chat_out(r) for r in rows], scope, limit)
|
||||
|
||||
|
||||
def is_member(conn, chat_id, user_id):
|
||||
return conn.execute('SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s',
|
||||
(chat_id, user_id)).fetchone() is not None
|
||||
|
||||
|
||||
def create_message(chat_id, sender_id, text, attachment_ids, key, request_hash, key_ttl_seconds):
|
||||
scope = 'POST /api/v1/chats/%s/messages' % chat_id
|
||||
with connection() as conn, conn.transaction():
|
||||
conn.execute('DELETE FROM idempotency_keys WHERE user_id = %s AND created_at < now() - make_interval(secs => %s)',
|
||||
(sender_id, key_ttl_seconds))
|
||||
claimed = conn.execute(
|
||||
'INSERT INTO idempotency_keys (user_id, scope, key, request_hash) VALUES (%s, %s, %s, %s) '
|
||||
'ON CONFLICT DO NOTHING RETURNING 1',
|
||||
(sender_id, scope, key, request_hash)).fetchone()
|
||||
if claimed is None:
|
||||
if not is_member(conn, chat_id, sender_id):
|
||||
raise ApiError(404, 'Чат не найден')
|
||||
stored = conn.execute(
|
||||
'SELECT k.request_hash, ' + MESSAGE_COLUMNS + ' '
|
||||
'FROM idempotency_keys k JOIN messages m ON m.id = k.message_id '
|
||||
'WHERE k.user_id = %s AND k.scope = %s AND k.key = %s',
|
||||
(sender_id, scope, key)).fetchone()
|
||||
if bytes(stored['request_hash']) != request_hash:
|
||||
raise ApiError(409, 'Idempotency-Key уже использован с другим запросом')
|
||||
return message_out(stored)
|
||||
row = conn.execute(
|
||||
'INSERT INTO messages AS m (chat_id, sender_id, text) SELECT %s, %s, %s '
|
||||
'WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s) '
|
||||
'RETURNING m.id, m.chat_id, m.sender_id, m.text, m.created_at',
|
||||
(chat_id, sender_id, utf8(text), chat_id, sender_id)).fetchone()
|
||||
if row is None:
|
||||
raise ApiError(404, 'Чат не найден')
|
||||
if attachment_ids:
|
||||
found = conn.execute("SELECT count(*) AS n FROM attachments WHERE id = ANY(%s::uuid[]) "
|
||||
"AND chat_id = %s AND status = 'ready'", (attachment_ids, chat_id)).fetchone()['n']
|
||||
if found != len(attachment_ids):
|
||||
raise ApiError(404, 'Вложение не найдено в этом чате')
|
||||
conn.execute('INSERT INTO message_attachments (message_id, attachment_id, position) '
|
||||
'SELECT %s, attachment, position FROM unnest(%s::uuid[]) WITH ORDINALITY AS t(attachment, position)',
|
||||
(row['id'], attachment_ids))
|
||||
row = dict(row, attachment_ids=attachment_ids)
|
||||
conn.execute('UPDATE idempotency_keys SET message_id = %s WHERE user_id = %s AND scope = %s AND key = %s',
|
||||
(row['id'], sender_id, scope, key))
|
||||
return message_out(row)
|
||||
|
||||
|
||||
def list_messages(chat_id, user_id, cursor, limit):
|
||||
scope = 'chat:' + chat_id
|
||||
sql = 'SELECT ' + MESSAGE_COLUMNS + ' FROM messages m WHERE m.chat_id = %s '
|
||||
params = [chat_id]
|
||||
if cursor:
|
||||
sql += 'AND (m.created_at, m.id) > (%s, %s) '
|
||||
params += decode_cursor(scope, cursor)
|
||||
sql += 'ORDER BY m.created_at, m.id LIMIT %s'
|
||||
with connection() as conn:
|
||||
if not is_member(conn, chat_id, user_id):
|
||||
raise ApiError(404, 'Чат не найден')
|
||||
rows = conn.execute(sql, params + [limit + 1]).fetchall()
|
||||
return page([message_out(r) for r in rows], scope, limit)
|
||||
|
||||
|
||||
def start_attachment(attachment_id, chat_id, owner_id, filename, content_type, size, sha256, object_key):
|
||||
with connection() as conn:
|
||||
if not is_member(conn, chat_id, owner_id):
|
||||
raise ApiError(404, 'Чат не найден')
|
||||
conn.execute("INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
|
||||
"object_key, status) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'uploading')",
|
||||
(attachment_id, chat_id, owner_id, filename, content_type, size, sha256, object_key))
|
||||
|
||||
|
||||
def finish_attachment(attachment_id):
|
||||
with connection() as conn:
|
||||
row = conn.execute("UPDATE attachments AS a SET status = 'ready', updated_at = clock_timestamp() "
|
||||
"WHERE a.id = %s AND a.status = 'uploading' RETURNING " + ATTACHMENT_COLUMNS,
|
||||
(attachment_id,)).fetchone()
|
||||
if row is None:
|
||||
raise ApiError(503, 'Загрузка не завершена, повторите')
|
||||
return attachment_out(row)
|
||||
|
||||
|
||||
def forget_attachment(attachment_id):
|
||||
with connection() as conn:
|
||||
conn.execute("DELETE FROM attachments WHERE id = %s AND status = 'uploading'", (attachment_id,))
|
||||
|
||||
|
||||
def check_member(chat_id, user_id):
|
||||
with connection() as conn:
|
||||
if not is_member(conn, chat_id, user_id):
|
||||
raise ApiError(404, 'Чат не найден')
|
||||
|
||||
|
||||
def get_attachment(attachment_id, user_id):
|
||||
with connection() as conn:
|
||||
row = conn.execute("SELECT " + ATTACHMENT_COLUMNS + " FROM attachments a "
|
||||
"JOIN chat_members me ON me.chat_id = a.chat_id AND me.user_id = %s "
|
||||
"WHERE a.id = %s AND a.status = 'ready'", (user_id, attachment_id)).fetchone()
|
||||
if row is None:
|
||||
raise ApiError(404, 'Вложение не найдено')
|
||||
return row
|
||||
Reference in New Issue
Block a user