Перенесите реализацию ЛР 4 на стенд ЛР 5

This commit is contained in:
2026-11-18 15:33:31 +03:00
parent 276dbdad8a
commit 911d97a77a
153 changed files with 17451 additions and 1 deletions
+76
View File
@@ -0,0 +1,76 @@
# The single entry point: round-robin over the API replicas found through
# Docker DNS, with active readiness checks and no client stickiness.
global
log stdout format raw local0 info
maxconn 20000
# The container has at most one CPU; by default HAProxy starts a thread
# per host CPU and fights the quota.
nbthread 1
defaults
mode http
log global
option dontlognull
timeout connect 1s
timeout client 30s
# Above the API's 5 s request deadline: the API answers a slow request
# itself, this only cuts off a hung replica.
timeout server 7s
timeout http-request 10s
timeout http-keep-alive 10s
timeout check 2s
# Below the 500 ms latency objective: excess load gets a fast 503.
timeout queue 300ms
# Re-sent only when nothing reached the API: a timeout or an empty
# response may follow a committed write.
retries 2
option redispatch 1
retry-on conn-failure
# Errors produced by the balancer itself use the contract's envelope.
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"the API replica failed to answer","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"no API replica is available","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"the API replica did not answer in time","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
# `api` resolves to every running replica, re-resolved every second; an
# address that disappears leaves at once.
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 10s
hold obsolete 0s
accepted_payload_size 8192
frontend entry
bind :8080
option httplog
unique-id-format %[uuid(4),regsub(-,,g)]
# Replaces any client value; the API keeps it, so one id spans both logs.
http-request set-header X-Request-Id %[unique-id]
capture response header X-Instance-Id len 32
capture response header X-Request-Id len 40
http-after-response set-log-level silent if { status lt 500 } { env(LB_QUIET) -m str 1 }
default_backend replicas
backend replicas
# Binary handlers have a 30s budget, ordinary API handlers retain 5s.
http-request set-timeout server 35s if { path_reg ^/api/v1/chats/[^/]+/attachments$|^/api/v1/attachments/[^/]+/content$ }
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
# Out within 1.5 s (inter + fastinter), less than the API's 2 s drain delay.
# maxconn 20: the replica's 10 pooled database connections plus requests
# that need no database; the rest waits in the queue.
default-server maxconn "${API_MAXCONN-20}" inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4
# Up to five replicas, doubled while docker rollout replaces them.
server-template api 10 api:8080
listen stats
bind :8404
no log
stats enable
stats uri /
stats refresh 2s
+77
View File
@@ -0,0 +1,77 @@
# Private object storage
`s3` runs SeaweedFS 4.53 in one process. The image is pinned by digest in
`compose.yaml` and `internal/testenv/s3.go`. `seaweedfs.options` is shared by
the stand and the disposable integration-test server.
S3 HTTP (8333) and SeaweedFS's companion gRPC (18333) listen on the private
container network. This image has no flag to disable the companion listener;
its identity-cache mutations reject remote peers, which the integration test
checks. Master, volume and filer HTTP/gRPC endpoints bind to loopback.
No host port is published. `/data`
contains both object volumes and the image's LevelDB filer metadata; the
named `s3data` volume must be retained together with PostgreSQL data.
Run `sh scripts/init-secrets.sh` before starting the stand. It preserves the
existing PostgreSQL and Valkey credentials and creates three independent S3
identities plus the static server configuration. Credential values are never
printed. Repeated initialization keeps all existing keys. Set `S3_BUCKET` in
the environment or the local `.env` before the first initialization; changing
it later requires a planned migration of identities and retained data.
The server loads its static identity secret before serving requests. There is
no anonymous identity. The bootstrap identity has administrative rights and
its individual key files are mounted only in `s3-init`. The API identity has
`Read:<bucket>` and `Write:<bucket>`; it cannot list objects or administer
buckets. The reconciler identity adds `List:<bucket>`. All three identities
are necessarily present in the S3 server's own identity configuration secret.
`s3-init` creates the bucket idempotently and waits for storage before API
replicas start. An anonymous 403 and bucket metadata alone do not prove that
retained volume locations have registered with the elected master. Bootstrap
first reads a persistent `.health/storage-v1` marker (creating it only when
absent), then verifies a fresh write/read/delete. This startup-only barrier
uses the caller's deadline, capped at 60 seconds; ordinary S3 operations and
API readiness do not retry through it. The marker is outside the reconciler's
`staging/` and `blobs/` namespaces. `scripts/restart.sh` already runs this
bootstrap before restoring API replicas.
The bootstrap uses `/usr/local/bin/s3init`. The optional `recon` profile runs
`/usr/local/bin/reconcile`, with reconciler credentials mapped to the standard
`S3_ACCESS_KEY_ID_FILE` and `S3_SECRET_ACCESS_KEY_FILE` paths:
```sh
docker compose --profile recon run --rm reconcile
docker compose --profile recon run --rm reconcile --apply
```
The API receives its own standard S3 key files. Its background reconciliation
worker must construct a separate store from
`S3_RECONCILE_ACCESS_KEY_ID_FILE` and `S3_RECONCILE_SECRET_ACCESS_KEY_FILE`;
listing with the API identity is denied. S3 is intentionally absent from API
readiness so text traffic can remain available during an object-store outage.
The S3 cgroup is limited to one CPU, 512 MiB, and 256 processes. Upload limits
are four concurrent requests and 64 MiB in flight; reader buffers have a
32 MiB budget and the chunk cache is disabled. Disk allocation is capped at
64 volumes of approximately 128 MiB each (with normal volume rollover
overhead); this is a lab capacity limit, not a filesystem quota.
Each API replica has 2 GiB and `GOMEMLIMIT=1536MiB`, with one image decoder.
Pixels alone are not the full budget: progressive JPEG retains coefficients,
and a wide RGBA64 PNG keeps two large scanlines beside its pixel buffer.
The 40 MP RGB/CMYK progressive JPEG and wide-PNG measurements are recorded in
`evidence/decoder-memory-*.json`; this does not change the S3 service's 512 MiB limit.
Verify the adapter and real server with Docker running:
```sh
go test -race -count=1 ./internal/platform/s3store
```
`testenv.StartS3(ctx)` returns `Store` with reconciler rights, `APIStore`,
`Admin`, endpoint and credentials. `Recreate(ctx)` replaces only its own
container while keeping its named volume and does not recreate the bucket.
It waits for the same retained-marker and write/read/delete barrier before
returning. `Start(ctx)` does so as well. Always call `Close()` to remove the
fixture's container and volume.
+31
View File
@@ -0,0 +1,31 @@
dir=/data
ip=127.0.0.1
ip.bind=127.0.0.1
master.telemetry=false
master.volumeSizeLimitMB=128
volume.port=9340
volume.max=64
volume.index=leveldb
volume.fileSizeLimitMB=10
volume.concurrentUploadLimitMB=64
volume.concurrentDownloadLimitMB=64
volume.readBufferSizeMB=1
volume.preStopSeconds=1
filer=true
filer.exposeDirectoryData=false
filer.disableDirListing=true
filer.concurrentFileUploadLimit=4
filer.concurrentUploadLimitMB=64
s3=true
s3.ip.bind=0.0.0.0
s3.port=8333
s3.config=/run/secrets/s3_identities
s3.autoCreateBucket=false
s3.iam=false
s3.port.iceberg=0
s3.port.lance=0
s3.concurrentFileUploadLimit=4
s3.concurrentUploadLimitMB=64
s3.readerCacheSizeMB=32
s3.cacheCapacityMB=0
s3.idleTimeout=35
+19
View File
@@ -0,0 +1,19 @@
# Valkey is the only store of user sessions, so it is their source of truth.
# Every write is fsynced before the reply: an acknowledged login survives a
# crash or a restart. Only logins and logouts write; session lookups are reads
# and pay nothing for this.
appendonly yes
appendfsync always
dir /data
# The append-only file already persists everything; RDB snapshots are off.
save ""
# Sessions are never evicted to free memory: once maxmemory is reached the
# store refuses new sessions (login answers 503) instead of silently logging
# users out. A session key takes about a hundred bytes.
maxmemory 256mb
maxmemory-policy noeviction
# requirepass comes from the compose secret, never from the repository.
include /run/secrets/valkey_auth