This commit is contained in:
2026-11-05 18:08:31 +03:00
parent ec540a1a72
commit d6e976e4c0
33 changed files with 2789 additions and 52 deletions
+47 -4
View File
@@ -1,7 +1,50 @@
# Инфраструктура студента
# Compose + Nginx + MinIO
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
The runnable topology is in the root `compose.yaml`. The example Compose file
and `contracts/infrastructure.json` are teaching worksheets, not deployments.
The supported local entry point is Nginx; API, PostgreSQL, Redis and MinIO ports
are not published to the host.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
| Role | Service / image | Persistence and readiness |
| --- | --- | --- |
| API | `api`, built from `Dockerfile` / Python 3.12.11 | Two stateless replicas; `/health/ready`; no host port |
| Load balancer | `nginx:1.27.5-alpine` | Host port `${APP_PORT:-8080}`; Docker DNS refresh 5 s; passive fail exclusion |
| Database | `postgres:16.8-alpine` | `postgres_data` named volume; `pg_isready` |
| Sessions | `redis:7.4.2-alpine` | `redis_data` named volume; AOF `everysec`; Redis `PING` |
| Object storage | MinIO `RELEASE.2025-09-07T16-13-09Z`, pinned by image digest in Compose | `minio_data` named volume; MinIO readiness endpoint; S3 port 9000 and console 9001 are private |
| Migration job | Same API image | Runs ordered SQL migrations once before API replicas |
| Bucket bootstrap | Same pinned MinIO image, using its `mc` client | Idempotently creates the private bucket, versioned policy, and restricted API user; replaces the prior policy without deleting volumes |
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
PostgreSQL and S3 hold different parts of an attachment: PostgreSQL is the source
of truth for metadata and access control; the private S3 bucket stores original
bytes under a random server-generated key. The bucket name is fixed as
`messenger-attachments`. No endpoint returns object keys or S3 credentials.
The MinIO root credentials are mounted only into MinIO and its one-shot bootstrap
job. The API receives a separate access key restricted to `GetBucketLocation`,
`ListBucket` with the `objects/` prefix, and Get/Put/Delete on `objects/*`.
The bootstrap grants no anonymous policy. Verify
that from inside the Compose network with
`py -3 -X utf8 student-tests/check_private_bucket.py`; it expects an unsigned
bucket-list request to receive HTTP 403 and confirms MinIO has no host port
binding. The administrative console is not exposed.
Create local ignored secrets using `scripts/init-local-secrets.ps1`; never copy
secrets from another lab. Do not rotate credentials while retaining the
corresponding database or MinIO volumes. `scripts/restart.bat` / `.sh` restarts
the API, database, Redis, MinIO and Nginx without deleting volumes.
`scripts/stop-one.bat` / `.sh` stops only the API container whose hostname equals
`TARGET_INSTANCE_ID` and leaves it stopped for the failover check.
Attachment writes reserve PostgreSQL metadata in `processing` state before
writing S3. On success, the row becomes `ready` and the API returns 201. Errors
attempt to delete the object and mark the reservation `failed`; if compensation
cannot reach either store, the processing row remains visible to reconciliation.
Run `scripts/reconcile_attachments.py` in dry-run mode first. It only acts on
records/objects older than a 15-minute minimum grace period, marks stale uploads
failed, deletes old unreferenced objects, and reports missing objects for ready
metadata. `--apply` is required for changes.
MinIO, PostgreSQL, Redis, Nginx, and the Docker host are single-instance
dependencies. This setup survives an API-replica failure and restarts with
volumes, not loss of the Docker host or an individual state-store volume.
+32
View File
@@ -0,0 +1,32 @@
#!/bin/sh
set -eu
root_user=$(cat /run/secrets/minio_root_user)
root_password=$(cat /run/secrets/minio_root_password)
service_user=$(cat /run/secrets/s3_access_key_id)
service_password=$(cat /run/secrets/s3_secret_access_key)
until mc alias set local http://minio:9000 "$root_user" "$root_password" >/dev/null 2>&1 \
&& mc ready local >/dev/null 2>&1; do
sleep 2
done
bucket=${S3_BUCKET:-messenger-attachments}
if [ "$bucket" != 'messenger-attachments' ]; then
printf '%s\n' 'S3_BUCKET must be messenger-attachments' >&2
exit 2
fi
policy=messenger-attachments-v2
legacy_policy=messenger-attachments
mc mb --ignore-existing "local/$bucket"
if ! mc admin policy info local "$policy" >/dev/null 2>&1; then
mc admin policy create local "$policy" /infra/s3-policy.json
fi
if ! mc admin user info local "$service_user" >/dev/null 2>&1; then
mc admin user add local "$service_user" "$service_password" >/dev/null
fi
mc admin policy attach local "$policy" --user "$service_user" >/dev/null
if mc admin policy info local "$legacy_policy" >/dev/null 2>&1; then
mc admin policy detach local "$legacy_policy" --user "$service_user" >/dev/null
mc admin policy remove local "$legacy_policy" >/dev/null
fi
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
export MINIO_ROOT_USER="$(cat /run/secrets/minio_root_user)"
export MINIO_ROOT_PASSWORD="$(cat /run/secrets/minio_root_password)"
exec minio server /data --address :9000 --console-address :9001
+26
View File
@@ -0,0 +1,26 @@
resolver 127.0.0.11 valid=5s ipv6=off;
upstream messenger_api {
zone messenger_api 64k;
server api:8080 resolve max_fails=1 fail_timeout=2s;
}
server {
listen 8080;
server_name _;
client_max_body_size 11m;
client_body_timeout 20s;
location / {
proxy_pass http://messenger_api;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_request_buffering off;
proxy_connect_timeout 2s;
proxy_send_timeout 20s;
proxy_read_timeout 20s;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::messenger-attachments"]
},
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::messenger-attachments"],
"Condition": {
"StringLike": {
"s3:prefix": ["objects/", "objects/*"]
}
}
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::messenger-attachments/objects/*"]
}
]
}