lab5: исправления по ревью

Concurrent complete no longer deletes the shared verified source; admission is atomic and covers pending presign rows; relay reconciles queued jobs lost to dead-lettering; failed staging is protected until failed_retention; timestamps normalized to UTC; reprocess prefers the durable original and keeps job->attachment lock order; heartbeat errors no longer burn attempts; confirm timeout enforced; pinned images and sanitized health responses.
This commit is contained in:
Vladislav Kunetskiy
2026-10-30 23:13:44 +03:00
parent 4bdcac3dfa
commit 9d7a0acb5a
40 changed files with 592 additions and 521 deletions
+1
View File
@@ -144,6 +144,7 @@ OUTBOX_POLL_INTERVAL=1s
OUTBOX_CLAIM_TTL=30s
OUTBOX_BATCH=20
OUTBOX_REAPER_INTERVAL=15s
OUTBOX_RECONCILE_AFTER=5m
OUTBOX_RETENTION=168h
RELAY_CPU_LIMIT=0.25
RELAY_MEM_LIMIT=128M
+29 -5
View File
@@ -67,6 +67,8 @@ flowchart LR
- **Relay** — отдельный процесс: читает outbox через `FOR UPDATE SKIP LOCKED`, публикует persistent
сообщение с publisher confirm, помечает `published_at` только после ack. Там же lease reaper:
просроченные `processing` возвращаются в `queued` с новым attempt, а исчерпавшие бюджет — в `failed`.
Дополнительно reaper переиздаёт `queued` jobs без unpublished outbox-строки (потерянная доставка,
dead-letter или data loss broker-а); worker CAS делает дубль безопасным.
- **Worker** — отдельный процесс/контейнер. Claim через CAS, heartbeat, обработка, запись S3,
затем одна транзакция результата; ack только после commit. Падение до ack приводит к redelivery;
повтор видит готовый эффект и делает no-op ack.
@@ -85,8 +87,10 @@ flowchart LR
- Sweeper status-aware: staging queued/processing не удаляется; ready staging удаляется после
безопасной фиксации; failed — после retention; orphan staging — после orphan grace. Referenced set
включает финальные объекты, variants и активный staging; keyset-пагинация, fail-closed.
- Admission control ограничивает число незавершённых jobs на пользователя/стенд и объём staged bytes
(429 `rate_limited`), чтобы 202 не превращался в неограниченную очередь.
- Admission control ограничивает число незавершённых rows (включая `pending` presign) на
пользователя/стенд и объём staged bytes (429 `rate_limited`). Проверка повторяется внутри
транзакции под PostgreSQL advisory lock, поэтому параллельные запросы не обходят cap; presign
использует тот же механизм.
### Соответствие `.env.example` реальной конфигурации
@@ -114,11 +118,21 @@ flowchart LR
| Outbox gap COMMIT→publish | `lab5_faults.py` | unpublished row → relay crash → recovery → published/ready | `evidence/lab5/faults.txt` |
| Lease зависшего processing | `lab5_faults.py` | pause worker → lease expiry → requeue → fence stale → ready | `evidence/lab5/faults.txt` |
| Persistence lab2+ | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS с broker/worker/relay в hook | `evidence/lab5/persistence.txt` |
| Failover lab3+ | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 97 успешных записей, 0 ошибок, recovery 1.2 s | `evidence/lab5/failover.txt` |
| Failover lab3+ | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 99 успешных записей, 0 ошибок, recovery 0.22 s | `evidence/lab5/failover.txt` |
| Idempotency lab3+ | `make test-idempotency` | 1 accepted, 11 conflicts, stable replay | `evidence/lab5/idempotency.txt` |
| LB исключает not-ready реплику | `make test-lb-readiness` | candidate 200→503, LB DOWN за 3 s, 40 запросов без candidate | `evidence/lab5/lb-readiness.txt` |
| LB исключает not-ready реплику | `make test-lb-readiness` | candidate 200→503, LB DOWN в пределах 30 s, 40 запросов без candidate | `evidence/lab5/lb-readiness.txt` |
| Трек 2: duplicate/stale/version | `python3 scripts/lab5_track2.py --reps 3` | 6/6 PASS: duplicate before effect, v1→v2, stale v1 no-op | `evidence/lab5/track2/` |
### Параметры кодирования вариантов
| pipeline_version | thumbnail/crop JPEG | optimized WebP | WebP method | EXIF/alpha |
| --- | --- | --- | --- | --- |
| 1 | quality 85 | quality 80 | 2 | EXIF orientation применяется; metadata удаляется повторным encode; alpha компонуется на белый для JPEG |
| 2 | quality 70 | quality 65 | 4 | то же |
Параметры закомпилированы в `internal/imageproc.Pipeline` и неизменны для версии; retry не может
получить другие байты. Optimized не увеличивает изображение, fit ≤1280×1280.
## Эксперименты и отказы
| Воздействие | Что ожидали | Что наблюдали |
@@ -149,7 +163,17 @@ flowchart LR
interleavings sampled, не исчерпаны.
- Presign — optional extension; его ответ 202 и проверенный staging описаны в отчёте, но публичный
контракт его не требует.
- Rate limiting — admission cap, не промышленный token bucket.
- Rate limiting — admission cap с транзакционным reservation, не промышленный token bucket.
- Presign подписывает URL статическим локальным app-identity; S3 API опубликован только на
loopback для учебного стенда. В production нужен отдельный least-privilege signer и запрет
локального доступа к bucket.
- API readiness проверяет PostgreSQL, не S3/broker: при отказе S3 upload отвечает 503, но
маршрутизация LB и чтение метаданных продолжают работать.
- Reconciliation потерянной доставки запускается через `OUTBOX_RECONCILE_AFTER` (5m), поэтому
dead-letter не теряет intent, но восстановление не мгновенное.
- Failpoints включаются только `FAULTS_ENABLED=1` при `APP_ENV=dev`; в обычном стенде инертны.
- `x-delivery-limit` — immutable queue argument. На чистом стенде создаётся 100; при обновлении
существующего volume очередь нужно пересоздать (или применить policy) до старта worker/relay.
- Старые lab4 ready-вложения не переобрабатываются миграцией; для них нужен ручной
`jobctl reprocess` (backfill в эту серию не входил).
+4 -3
View File
@@ -162,6 +162,7 @@ func run(cfg config.Config, log *slog.Logger) error {
ClaimTTL: cfg.Outbox.ClaimTTL,
Batch: cfg.Outbox.Batch,
ReaperInterval: cfg.Outbox.ReaperInterval,
ReconcileAfter: cfg.Outbox.ReconcileAfter,
Retention: cfg.Outbox.Retention,
}, log)
@@ -212,14 +213,14 @@ func healthServer(
defer cancel()
if err := store.Ping(ctx); err != nil {
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable", "database": err.Error()})
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
return
}
if !pub.Connected() {
if err := pub.Connect(); err != nil {
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable", "broker": err.Error()})
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
return
}
@@ -227,7 +228,7 @@ func healthServer(
oldest, err := relay.Health(ctx)
if err != nil {
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable", "outbox": err.Error()})
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
return
}
+3 -6
View File
@@ -79,7 +79,6 @@ func run(cfg config.Config, log *slog.Logger) error {
RetryCap: cfg.Processing.RetryCap,
MaxUploadBytes: cfg.S3.MaxUploadBytes,
MaxImagePixels: cfg.S3.MaxImagePixels,
Owner: fmt.Sprintf("worker-%d", os.Getpid()),
}, log)
server := healthServer(cfg.Worker.HealthAddr, store, objectStore, workerInstance)
@@ -197,22 +196,20 @@ func healthServer(
defer cancel()
if err := store.Ping(ctx); err != nil {
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable", "database": err.Error()})
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
return
}
if err := objectStore.Ping(ctx); err != nil {
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable", "s3": err.Error()})
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
return
}
running, connected := workerInstance.Ready()
if !running || !connected {
writeHealth(w, http.StatusServiceUnavailable, map[string]any{
"status": "unavailable", "consumer": running, "broker": connected,
})
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
return
}
+4 -3
View File
@@ -43,7 +43,7 @@ services:
restart: unless-stopped
redis:
image: redis:7.4-alpine
image: redis:7.4-alpine@sha256:858f009f9709ce576febc734aa78b8f6d624b82571f9ddb6bda4377c833b3499
command:
- redis-server
- --appendonly
@@ -105,7 +105,7 @@ services:
# Durable job transport. Quorum queues, publisher confirms and a DLQ live in
# the broker; PostgreSQL's outbox remains the source of truth for intent.
broker:
image: rabbitmq:4.3.7-management-alpine
image: rabbitmq:4.3.7-management-alpine@sha256:1528a88eebf2bc4d0ab7e9d5d9bc542e9bdf5e1b105e65848fcf8de5c2186528
hostname: broker
environment:
RABBITMQ_DEFAULT_USER: ${BROKER_USER:-messenger}
@@ -353,6 +353,7 @@ services:
OUTBOX_CLAIM_TTL: ${OUTBOX_CLAIM_TTL:-30s}
OUTBOX_BATCH: ${OUTBOX_BATCH:-20}
OUTBOX_REAPER_INTERVAL: ${OUTBOX_REAPER_INTERVAL:-15s}
OUTBOX_RECONCILE_AFTER: ${OUTBOX_RECONCILE_AFTER:-5m}
OUTBOX_RETENTION: ${OUTBOX_RETENTION:-168h}
RELAY_HEALTH_ADDR: ":8082"
FAULTS_ENABLED: ${FAULTS_ENABLED:-0}
@@ -384,7 +385,7 @@ services:
# Public entry point. Active /health/ready probes remove a not-ready replica from
# rotation entirely; infra/lb/haproxy.cfg holds the upstream, checks and retries.
lb:
image: haproxy:3.2-alpine
image: haproxy:3.2-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122
volumes:
- ./infra/lb/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
ports:
+2 -2
View File
@@ -23,7 +23,7 @@ services:
start_period: 5s
restart: unless-stopped
redis:
image: redis:7.4-alpine
image: redis:7.4-alpine@sha256:858f009f9709ce576febc734aa78b8f6d624b82571f9ddb6bda4377c833b3499
command:
- redis-server
- --appendonly
@@ -67,7 +67,7 @@ services:
broker:
image: rabbitmq:4.3.7-management-alpine
image: rabbitmq:4.3.7-management-alpine@sha256:1528a88eebf2bc4d0ab7e9d5d9bc542e9bdf5e1b105e65848fcf8de5c2186528
hostname: broker
environment:
RABBITMQ_DEFAULT_USER: ${BROKER_USER:-messenger}
+2 -2
View File
@@ -1,5 +1,5 @@
# lab5_async 2026-10-30T19:29:41Z
worker down: 202 queued, content 409, queued attachment linked
# lab5_async 2026-10-30T20:08:22Z
worker down: 202 queued, content 409, queued attachment linked, API restarted
worker restarted: ready, thumbnail and original downloadable, staging cleared
broker down: upload accepted into outbox
broker + relay recovered: queued job reached ready
+1 -1
View File
@@ -1,4 +1,4 @@
# attachments negative 2026-10-30T19:32:35Z
# attachments negative 2026-10-30T20:11:40Z
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 student-tests/attachments_negative.py --base-url "http://localhost:8080"
10 MiB + 1 body: 413
empty body: 415
+8 -8
View File
@@ -1,29 +1,29 @@
# db state 2026-10-30T19:34:38Z
# db state 2026-10-30T20:13:30Z
status | count
---------+-------
failed | 8
failed | 2
pending | 4
ready | 74
ready | 25
(3 rows)
status | count
--------+-------
failed | 8
ready | 81
failed | 2
ready | 28
(2 rows)
variants
----------
243
84
(1 row)
unpublished | outbox
-------------+--------
0 | 150
0 | 52
(1 row)
Timeout: 60.0 seconds ...
Listing queues for vhost messenger ...
name messages messages_ready messages_unacknowledged consumers
attachment.process.dead 12 12 0 0
attachment.process.dead 4 4 0 0
attachment.process.v1 0 0 0 1
+2 -2
View File
@@ -1,5 +1,5 @@
# failover 2026-10-30T19:32:39Z
# failover 2026-10-30T20:11:43Z
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 98, "failed_attempts": 0, "first_recovery_seconds": 2.34}
{"observed_instances_before": 2, "successful_writes": 99, "failed_attempts": 0, "first_recovery_seconds": 0.221}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
+1 -1
View File
@@ -1,4 +1,4 @@
# fault injection 2026-10-30T19:30:35Z
# fault injection 2026-10-30T20:09:37Z
permanent failure: failed/injected_failure, content 409, failed attachment not linkable, registry visible
replay: failed -> queued -> ready, one thumbnail
replay ready job: refused
+2 -2
View File
@@ -1,4 +1,4 @@
# idempotency 2026-10-30T19:32:39Z
# idempotency 2026-10-30T20:11:43Z
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 student-tests/idempotency_parallel.py --base-url "http://localhost:8080"
{"replay": {"workers": 12, "instances": ["5012b453c822", "63bc0da849d5"], "message_id": "01a18e4c-cb55-7c5f-a0e3-f3285329e15b"}, "conflict": {"workers": 12, "accepted": 1, "conflicts": 11}, "stable_body": {"message_id": "01a18e4c-cb87-70be-889e-b4b781fc7d0f"}, "key_required": {"status": 400}}
{"replay": {"workers": 12, "instances": ["1c67613c89f2", "ee96975adb44"], "message_id": "01a18e70-8fcd-7519-91ab-d9c43b6a5f37"}, "conflict": {"workers": 12, "accepted": 1, "conflicts": 11}, "stable_body": {"message_id": "01a18e70-8ff9-759f-ab87-abd58f58c59d"}, "key_required": {"status": 400}}
PASS: параллельный повтор с одним Idempotency-Key создаёт ровно одно сообщение
+2 -2
View File
@@ -1,2 +1,2 @@
ok mtusi-messenger/internal/storage/postgres 8.124s
ok mtusi-messenger/internal/storage/redis 1.122s
ok mtusi-messenger/internal/storage/postgres 8.934s
ok mtusi-messenger/internal/storage/redis 1.229s
+15 -15
View File
@@ -1,34 +1,34 @@
# lb readiness 2026-10-30T19:33:46Z
# lb readiness 2026-10-30T20:10:40Z
scripts/lb_readiness_check.sh
# LB excludes a not-ready but reachable replica (lab5)
# generated: 2026-10-30T19:33:46Z
# lb: haproxy:3.2-alpine
# generated: 2026-10-30T20:10:40Z
# lb: haproxy:3.2-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122
## 1. baseline: requests through LB by replica
23 5012b453c822
17 63bc0da849d5
stats: api1=UP 1/2 api2=UP api3=MAINT (resolution) api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
19 1c67613c89f2
21 ee96975adb44
stats: api1=UP api2=MAINT (resolution) api3=UP api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
## 2. start a temporary TCP proxy to postgres and a candidate replica behind the same network alias
instance-id: 4da30d29f490, readiness while its database is reachable: 200
load balancer slot for the candidate: api1, stats: api1=UP api2=UP api3=UP api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
instance-id: 6dff747ee488, readiness while its database is reachable: 200
load balancer slot for the candidate: api2, stats: api1=UP api2=UP 1/2 api3=UP api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
## 3. cut the candidate's database access (stop only the TCP proxy)
candidate is still running: running, readiness: 503
waiting for the load balancer to mark api1 DOWN
WARNING: api1 is still not DOWN
stats after failure: api1=UP api2=UP api3=DOWN api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
waiting for the load balancer to mark api2 DOWN
api2 went DOWN 0s after its database was cut (check: inter 2s fall 2)
stats after failure: api1=UP api2=DOWN api3=UP api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
## 4. 40 requests through LB while the candidate is not ready
18 5012b453c822
22 63bc0da849d5
23 1c67613c89f2
17 ee96975adb44
(the candidate must not appear above)
## 5. business writes through LB during the exclusion
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 810.163,
"successful_rps": 746.262,
## 6. cleanup
stats after cleanup: api1=UP api2=UP api3=MAINT (resolution) api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
stats after cleanup: api1=UP api2=MAINT (resolution) api3=UP api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
lb_readiness_check.sh: evidence in evidence/lb-readiness.txt
+11 -11
View File
@@ -3,18 +3,18 @@ level=info msg="golangci-lint has version 2.13.2 built with go1.27.1 from (unkno
level=info msg="[config_reader] Config search paths: [./ /Users/vladislav/Projects/mtusi2026lab5 /Users/vladislav/Projects /Users/vladislav /Users /]"
level=info msg="[config_reader] Used config file .golangci.yml"
level=info msg="[config_reader] Module name \"mtusi-messenger\""
level=info msg="[goenv] Read go env for 5.612667ms: map[string]string{\"GOCACHE\":\"/Users/vladislav/Library/Caches/go-build\", \"GOROOT\":\"/opt/homebrew/Cellar/go/1.27.1/libexec\"}"
level=info msg="[goenv] Read go env for 5.643458ms: map[string]string{\"GOCACHE\":\"/Users/vladislav/Library/Caches/go-build\", \"GOROOT\":\"/opt/homebrew/Cellar/go/1.27.1/libexec\"}"
level=info msg="[lintersdb] Active 50 linters: [asasalint bodyclose canonicalheader containedctx contextcheck copyloopvar depguard durationcheck errcheck errname errorlint exhaustive exptostd fatcontext forbidigo forcetypeassert gocheckcompilerdirectives gocritic gofumpt goimports gomoddirectives gosec govet ineffassign intrange makezero misspell musttag nilerr nilnil noctx nolintlint perfsprint prealloc reassign recvcheck revive rowserrcheck sloglint sqlclosecheck staticcheck testifylint thelper tparallel unconvert unparam unused usestdlibvars usetesting wastedassign]"
level=info msg="[loader] Using build tags: [integration]"
level=info msg="[loader] Go packages loading at mode 8767 (compiled_files|deps|exports_file|imports|name|types_sizes|files) took 241.235292ms"
level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 11.528667ms"
level=info msg="[linters_context/goanalysis] analyzers took 2.426723836s with top 10 stages: revive: 891.424584ms, goimports: 197.31775ms, gosec: 134.79375ms, wastedassign: 101.139582ms, ctrlflow: 56.356778ms, gocritic: 43.448751ms, unparam: 40.089709ms, sloglint: 32.727792ms, ineffassign: 32.149583ms, directives: 31.348126ms"
level=info msg="[runner/exclusion_rules] Skipped 7 issues by rules: [Path: \"_test\\\\.go\", Linters: \"gosec, prealloc, forcetypeassert, unparam\"]"
level=info msg="[runner] Issues before processing: 889, after processing: 0"
level=info msg="[runner] Processors filtering stat (in/out): path_absoluter: 889/889, nolint_filter: 6/0, filename_unadjuster: 889/889, invalid_issue: 889/889, exclusion_rules: 302/6, cgo: 889/889, exclusion_paths: 889/889, generated_file_filter: 889/302, path_relativity: 889/889"
level=info msg="[runner] processing took 3.421128ms with stages: generated_file_filter: 2.333667ms, nolint_filter: 532.749µs, path_relativity: 260.5µs, exclusion_rules: 259.916µs, invalid_issue: 12.625µs, cgo: 12.125µs, path_absoluter: 5.042µs, filename_unadjuster: 2.626µs, sort_results: 500ns, max_same_issues: 250ns, exclusion_paths: 209ns, fixer: 167ns, path_prettifier: 167ns, path_shortener: 126ns, source_code: 125ns, max_per_file_from_linter: 125ns, diff: 84ns, max_from_linter: 42ns, severity-rules: 42ns, uniq_by_line: 41ns"
level=info msg="[runner] linters took 1.269085s with stages: goanalysis_metalinter: 1.265620125s"
level=info msg="[loader] Go packages loading at mode 8767 (files|imports|name|compiled_files|deps|exports_file|types_sizes) took 210.149917ms"
level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 11.759541ms"
level=info msg="[linters_context/goanalysis] analyzers took 0s with no stages"
level=info msg="[runner/exclusion_rules] Skipped 8 issues by rules: [Path: \"_test\\\\.go\", Linters: \"gosec, prealloc, forcetypeassert, unparam\"]"
level=info msg="[runner] Issues before processing: 881, after processing: 0"
level=info msg="[runner] Processors filtering stat (in/out): exclusion_paths: 881/881, nolint_filter: 6/0, path_absoluter: 881/881, invalid_issue: 881/881, generated_file_filter: 881/292, cgo: 881/881, filename_unadjuster: 881/881, path_relativity: 881/881, exclusion_rules: 292/6"
level=info msg="[runner] processing took 2.916079ms with stages: generated_file_filter: 1.448166ms, nolint_filter: 891.875µs, exclusion_rules: 277.041µs, path_relativity: 263.459µs, invalid_issue: 13.082µs, cgo: 11.375µs, path_absoluter: 4.792µs, filename_unadjuster: 2.875µs, max_same_issues: 958ns, sort_results: 750ns, exclusion_paths: 500ns, fixer: 458ns, path_shortener: 167ns, max_per_file_from_linter: 125ns, source_code: 125ns, path_prettifier: 125ns, diff: 83ns, max_from_linter: 41ns, severity-rules: 41ns, uniq_by_line: 41ns"
level=info msg="[runner] linters took 627.484792ms with stages: goanalysis_metalinter: 624.525167ms"
0 issues.
level=info msg="File cache stats: 0 entries of total size 0B"
level=info msg="Memory: 17 samples, avg is 140.2MB, max is 244.9MB"
level=info msg="Execution took 1.52797275s"
level=info msg="Memory: 10 samples, avg is 84.0MB, max is 111.1MB"
level=info msg="Execution took 856.003459ms"
+1 -1
View File
@@ -1,4 +1,4 @@
# persistence 2026-10-30T19:33:01Z
# persistence 2026-10-30T20:12:05Z
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
+1 -1
View File
@@ -1,4 +1,4 @@
# presign 2026-10-30T19:32:37Z
# presign 2026-10-30T20:11:41Z
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 student-tests/presign_flow.py --base-url "http://localhost:8080"
happy path: direct PUT 200, complete queued, ready after worker
message with attachment downloaded as the second chat member
+1 -1
View File
@@ -1,3 +1,3 @@
# make test 2026-10-30T19:29:39Z
# make test 2026-10-30T20:08:03Z
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
+12 -12
View File
@@ -1,16 +1,16 @@
# stand 2026-10-30T19:34:37Z
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
mtusi-messenger-lab5-api-1 mtusi-messenger:lab5 "/usr/local/bin/mess…" api 5 minutes ago Up 58 seconds (healthy) 8080/tcp
mtusi-messenger-lab5-api-2 mtusi-messenger:lab5 "/usr/local/bin/mess…" api 5 minutes ago Up 58 seconds (healthy) 8080/tcp
mtusi-messenger-lab5-broker-1 rabbitmq:4.3.7-management-alpine "docker-entrypoint.s…" broker 47 minutes ago Up About a minute (healthy) 4369/tcp, 5671-5672/tcp, 15671/tcp, 15691-15692/tcp, 25672/tcp, 127.0.0.1:15672->15672/tcp
mtusi-messenger-lab5-lb-1 haproxy:3.2-alpine "docker-entrypoint.s…" lb 47 minutes ago Up 53 seconds 127.0.0.1:8404->8404/tcp, 127.0.0.1:8080->80/tcp
mtusi-messenger-lab5-postgres-1 postgres:18-alpine@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873 "docker-entrypoint.s…" postgres 7 minutes ago Up About a minute (healthy) 5432/tcp
mtusi-messenger-lab5-redis-1 redis:7.4-alpine "docker-entrypoint.s…" redis 47 minutes ago Up About a minute (healthy) 6379/tcp
mtusi-messenger-lab5-relay-1 mtusi-messenger:lab5 "/usr/local/bin/relay" relay 2 minutes ago Up 58 seconds (healthy) 8080/tcp, 127.0.0.1:8082->8082/tcp
mtusi-messenger-lab5-seaweedfs-1 chrislusf/seaweedfs:3.80@sha256:1055999e08eed1789b0ae45d235126e4495e23d3fb9d6396293fd42539b1ae6a "/entrypoint.sh serv…" seaweedfs 46 minutes ago Up About a minute (healthy) 7333/tcp, 8080/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp, 127.0.0.1:8333->8333/tcp
mtusi-messenger-lab5-worker-1 mtusi-messenger:lab5 "/usr/local/bin/work…" worker 2 minutes ago Up 58 seconds (healthy) 8080/tcp, 127.0.0.1:8081->8081/tcp
# stand 2026-10-30T20:13:29Z
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
mtusi-messenger-lab5-api-1 mtusi-messenger:lab5 "/usr/local/bin/mess…" api 6 minutes ago Up 46 seconds (healthy) 8080/tcp
mtusi-messenger-lab5-api-2 mtusi-messenger:lab5 "/usr/local/bin/mess…" api 6 minutes ago Up 46 seconds (healthy) 8080/tcp
mtusi-messenger-lab5-broker-1 rabbitmq:4.3.7-management-alpine@sha256:1528a88eebf2bc4d0ab7e9d5d9bc542e9bdf5e1b105e65848fcf8de5c2186528 "docker-entrypoint.s…" broker 6 minutes ago Up About a minute (healthy) 4369/tcp, 5671-5672/tcp, 15671/tcp, 15691-15692/tcp, 25672/tcp, 127.0.0.1:15672->15672/tcp
mtusi-messenger-lab5-lb-1 haproxy:3.2-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 "docker-entrypoint.s…" lb 6 minutes ago Up 40 seconds 127.0.0.1:8404->8404/tcp, 127.0.0.1:8080->80/tcp
mtusi-messenger-lab5-postgres-1 postgres:18-alpine@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873 "docker-entrypoint.s…" postgres 6 minutes ago Up About a minute (healthy) 5432/tcp
mtusi-messenger-lab5-redis-1 redis:7.4-alpine@sha256:858f009f9709ce576febc734aa78b8f6d624b82571f9ddb6bda4377c833b3499 "docker-entrypoint.s…" redis 6 minutes ago Up About a minute (healthy) 6379/tcp
mtusi-messenger-lab5-relay-1 mtusi-messenger:lab5 "/usr/local/bin/relay" relay About a minute ago Up 46 seconds (healthy) 8080/tcp, 127.0.0.1:8082->8082/tcp
mtusi-messenger-lab5-seaweedfs-1 chrislusf/seaweedfs:3.80@sha256:1055999e08eed1789b0ae45d235126e4495e23d3fb9d6396293fd42539b1ae6a "/entrypoint.sh serv…" seaweedfs 6 minutes ago Up About a minute (healthy) 7333/tcp, 8080/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp, 127.0.0.1:8333->8333/tcp
mtusi-messenger-lab5-worker-1 mtusi-messenger:lab5 "/usr/local/bin/work…" worker About a minute ago Up 46 seconds (healthy) 8080/tcp, 127.0.0.1:8081->8081/tcp
mtusi-messenger:lab5 bc5f51c66c24
mtusi-messenger:lab5 a637d8b7d2d2
rabbitmq:4.3.7-management-alpine 1528a88eebf2
haproxy:3.2-alpine 254e6370f01c
redis:7.4-alpine 858f009f9709
+3 -3
View File
@@ -1,7 +1,7 @@
scenario,rep,pass,detail
duplicate_before_effect,1,1,attempts=1
stale_version_after_v2,1,1,v1_job=01a18e4a-6bff-7166-a56b-3ee5bc7fad9f
stale_version_after_v2,1,1,v1_job=01a18e6e-17b0-763b-b330-7adbcb43a700
duplicate_before_effect,2,1,attempts=1
stale_version_after_v2,2,1,v1_job=01a18e4a-9b1b-77ea-8d49-6d14e6b628fe
stale_version_after_v2,2,1,v1_job=01a18e6e-455e-75f3-857a-750ed660378b
duplicate_before_effect,3,1,attempts=1
stale_version_after_v2,3,1,v1_job=01a18e4a-c897-7b9f-83f6-951a71696d39
stale_version_after_v2,3,1,v1_job=01a18e6e-74f2-7b4a-842b-c014c626413c
1 scenario rep pass detail
2 duplicate_before_effect 1 1 attempts=1
3 stale_version_after_v2 1 1 v1_job=01a18e4a-6bff-7166-a56b-3ee5bc7fad9f v1_job=01a18e6e-17b0-763b-b330-7adbcb43a700
4 duplicate_before_effect 2 1 attempts=1
5 stale_version_after_v2 2 1 v1_job=01a18e4a-9b1b-77ea-8d49-6d14e6b628fe v1_job=01a18e6e-455e-75f3-857a-750ed660378b
6 duplicate_before_effect 3 1 attempts=1
7 stale_version_after_v2 3 1 v1_job=01a18e4a-c897-7b9f-83f6-951a71696d39 v1_job=01a18e6e-74f2-7b4a-842b-c014c626413c
+17 -17
View File
@@ -6,35 +6,35 @@ env -u APP_ENV -u SERVER_HOST -u SERVER_PORT -u SERVER_READ_HEADER_TIMEOUT -u SE
? mtusi-messenger/cmd/s3init [no test files]
? mtusi-messenger/cmd/worker [no test files]
? mtusi-messenger/internal/broker [no test files]
ok mtusi-messenger/internal/config 1.470s
ok mtusi-messenger/internal/domain 1.621s
ok mtusi-messenger/internal/config 2.441s
ok mtusi-messenger/internal/domain 1.484s
? mtusi-messenger/internal/failpoint [no test files]
ok mtusi-messenger/internal/health 2.890s
ok mtusi-messenger/internal/imagecheck 2.373s
ok mtusi-messenger/internal/imageproc 2.240s
ok mtusi-messenger/internal/logger 3.288s
ok mtusi-messenger/internal/health 2.069s
ok mtusi-messenger/internal/imagecheck 1.809s
ok mtusi-messenger/internal/imageproc 3.094s
ok mtusi-messenger/internal/logger 2.975s
? mtusi-messenger/internal/outbox [no test files]
ok mtusi-messenger/internal/platform/cache 3.207s
ok mtusi-messenger/internal/platform/cache 3.522s
? mtusi-messenger/internal/platform/cache/mocks [no test files]
ok mtusi-messenger/internal/platform/objectstore 3.773s
ok mtusi-messenger/internal/platform/password 2.523s
ok mtusi-messenger/internal/platform/token 2.532s
ok mtusi-messenger/internal/service/attachment 2.729s
ok mtusi-messenger/internal/platform/objectstore 5.364s
ok mtusi-messenger/internal/platform/password 4.551s
ok mtusi-messenger/internal/platform/token 4.459s
ok mtusi-messenger/internal/service/attachment 5.686s
? mtusi-messenger/internal/service/attachment/mocks [no test files]
ok mtusi-messenger/internal/service/chat 2.019s
ok mtusi-messenger/internal/service/chat 3.610s
? mtusi-messenger/internal/service/chat/mocks [no test files]
ok mtusi-messenger/internal/service/message 3.609s
ok mtusi-messenger/internal/service/message 3.931s
? mtusi-messenger/internal/service/message/mocks [no test files]
ok mtusi-messenger/internal/service/session 4.238s
ok mtusi-messenger/internal/service/session 5.387s
? mtusi-messenger/internal/service/session/mocks [no test files]
ok mtusi-messenger/internal/service/user 1.365s
ok mtusi-messenger/internal/service/user 4.965s
? mtusi-messenger/internal/service/user/mocks [no test files]
ok mtusi-messenger/internal/storage/postgres 4.021s
ok mtusi-messenger/internal/storage/postgres 5.965s
? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files]
? mtusi-messenger/internal/storage/postgres/migrations [no test files]
? mtusi-messenger/internal/storage/redis [no test files]
? mtusi-messenger/internal/storage/redis/mocks [no test files]
ok mtusi-messenger/internal/transport/rest 4.311s
ok mtusi-messenger/internal/transport/rest 6.275s
? mtusi-messenger/internal/transport/rest/internal/oas [no test files]
? mtusi-messenger/internal/transport/rest/mocks [no test files]
? mtusi-messenger/internal/worker [no test files]
+1 -1
View File
@@ -1,3 +1,3 @@
# lab5_variants 2026-10-30T19:29:54Z
# lab5_variants 2026-10-30T20:08:36Z
variants: thumbnail 256x160, crop 128x128, optimized WebP 320x200; metadata == bytes
PASS: lab5 variant contract
+14 -14
View File
@@ -1,31 +1,31 @@
# LB excludes a not-ready but reachable replica (lab5)
# generated: 2026-10-30T19:33:46Z
# lb: haproxy:3.2-alpine
# generated: 2026-10-30T20:10:40Z
# lb: haproxy:3.2-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122
## 1. baseline: requests through LB by replica
23 5012b453c822
17 63bc0da849d5
stats: api1=UP 1/2 api2=UP api3=MAINT (resolution) api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
19 1c67613c89f2
21 ee96975adb44
stats: api1=UP api2=MAINT (resolution) api3=UP api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
## 2. start a temporary TCP proxy to postgres and a candidate replica behind the same network alias
instance-id: 4da30d29f490, readiness while its database is reachable: 200
load balancer slot for the candidate: api1, stats: api1=UP api2=UP api3=UP api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
instance-id: 6dff747ee488, readiness while its database is reachable: 200
load balancer slot for the candidate: api2, stats: api1=UP api2=UP 1/2 api3=UP api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
## 3. cut the candidate's database access (stop only the TCP proxy)
candidate is still running: running, readiness: 503
waiting for the load balancer to mark api1 DOWN
WARNING: api1 is still not DOWN
stats after failure: api1=UP api2=UP api3=DOWN api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
waiting for the load balancer to mark api2 DOWN
api2 went DOWN 0s after its database was cut (check: inter 2s fall 2)
stats after failure: api1=UP api2=DOWN api3=UP api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
## 4. 40 requests through LB while the candidate is not ready
18 5012b453c822
22 63bc0da849d5
23 1c67613c89f2
17 ee96975adb44
(the candidate must not appear above)
## 5. business writes through LB during the exclusion
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 810.163,
"successful_rps": 746.262,
## 6. cleanup
stats after cleanup: api1=UP api2=UP api3=MAINT (resolution) api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
stats after cleanup: api1=UP api2=MAINT (resolution) api3=UP api4=MAINT (resolution) api5=MAINT (resolution) api6=MAINT (resolution) api7=MAINT (resolution) api8=MAINT (resolution) BACKEND=UP
+9 -2
View File
@@ -113,7 +113,7 @@ func declareTopology(channel *amqp.Channel, cfg Config) error {
queue, err := channel.QueueDeclare(cfg.Queue, true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
"x-delivery-limit": int32(8),
"x-delivery-limit": int32(100),
"x-delayed-retry-type": "all",
"x-delayed-retry-min": int32(5000),
"x-delayed-retry-max": int32(60000),
@@ -186,7 +186,14 @@ func (c *Client) PublishConfirmed(ctx context.Context, routingKey string, messag
return fmt.Errorf("publish job: %w", err)
}
confirmed, err := confirmation.WaitContext(ctx)
confirmCtx := ctx
if c.cfg.ConfirmTimeout > 0 {
var cancel context.CancelFunc
confirmCtx, cancel = context.WithTimeout(ctx, c.cfg.ConfirmTimeout)
defer cancel()
}
confirmed, err := confirmation.WaitContext(confirmCtx)
if err != nil {
return fmt.Errorf("await publisher confirm: %w", err)
}
+1
View File
@@ -79,6 +79,7 @@ type Outbox struct {
ClaimTTL time.Duration `mapstructure:"claim_ttl" validate:"required,gt=0"`
Batch int `mapstructure:"batch" validate:"required,gt=0,lte=1000"`
ReaperInterval time.Duration `mapstructure:"reaper_interval" validate:"required,gt=0"`
ReconcileAfter time.Duration `mapstructure:"reconcile_after" validate:"omitempty,gt=0"`
Retention time.Duration `mapstructure:"retention" validate:"required,gt=0"`
}
+7
View File
@@ -107,6 +107,13 @@ type Attachment struct {
FailedAt *time.Time
}
// AdmissionLimits bounds accepted-but-unfinished work. Zero means unlimited.
type AdmissionLimits struct {
PerUser int
Total int
Bytes int64
}
// AttachmentDraft is a fully validated attachment awaiting persistence.
type AttachmentDraft struct {
ID uuid.UUID
+6 -1
View File
@@ -15,7 +15,12 @@ import (
// Enabled reports whether fault injection is explicitly switched on.
func Enabled() bool {
return os.Getenv("FAULTS_ENABLED") == "1"
if os.Getenv("FAULTS_ENABLED") != "1" {
return false
}
env := os.Getenv("APP_ENV")
return env == "" || env == "dev"
}
// Check exits the process if the action is armed for this job. It must be
+13
View File
@@ -17,6 +17,7 @@ type Repository interface {
ReleaseOutbox(ctx context.Context, id int64, reason string) error
ReapOutboxClaims(ctx context.Context) error
ReapExpiredLeases(ctx context.Context, limit int) (int, error)
ReconcileQueuedJobs(ctx context.Context, olderThan time.Duration, limit int) (int, error)
PruneOutbox(ctx context.Context, retention time.Duration) error
OldestUnpublished(ctx context.Context) (time.Time, error)
}
@@ -31,6 +32,7 @@ type Config struct {
ClaimTTL time.Duration
Batch int
ReaperInterval time.Duration
ReconcileAfter time.Duration
Retention time.Duration
}
@@ -130,6 +132,17 @@ func (r *Relay) reap(ctx context.Context) {
r.log.InfoContext(ctx, "expired job leases requeued", slog.Int("count", reaped))
}
// The broker is not the source of truth. If a delivery was dead-lettered
// or lost, the queued job has no unpublished outbox row; republish it.
if r.config.ReconcileAfter > 0 {
reconciled, err := r.repo.ReconcileQueuedJobs(ctx, r.config.ReconcileAfter, 100)
if err != nil {
r.log.WarnContext(ctx, "queued-job reconciliation failed", slog.Any("error", err))
} else if reconciled > 0 {
r.log.InfoContext(ctx, "lost queued jobs reconciled", slog.Int("count", reconciled))
}
}
if r.config.Retention > 0 {
if err := r.repo.PruneOutbox(ctx, r.config.Retention); err != nil {
r.log.WarnContext(ctx, "outbox retention failed", slog.Any("error", err))
+36 -24
View File
@@ -229,8 +229,8 @@ func (_c *MockRepository_CompletePresign_Call) RunAndReturn(run func(ctx context
}
// CreatePresign provides a mock function for the type MockRepository
func (_mock *MockRepository) CreatePresign(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft)
func (_mock *MockRepository) CreatePresign(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, limits)
if len(ret) == 0 {
panic("no return value specified for CreatePresign")
@@ -238,16 +238,16 @@ func (_mock *MockRepository) CreatePresign(ctx context.Context, draft domain.Att
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, limits)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft) domain.Attachment); ok {
r0 = returnFunc(ctx, draft)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, limits)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft) error); ok {
r1 = returnFunc(ctx, draft)
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) error); ok {
r1 = returnFunc(ctx, draft, limits)
} else {
r1 = ret.Error(1)
}
@@ -262,11 +262,12 @@ type MockRepository_CreatePresign_Call struct {
// CreatePresign is a helper method to define mock.On call
// - ctx context.Context
// - draft domain.AttachmentDraft
func (_e *MockRepository_Expecter) CreatePresign(ctx any, draft any) *MockRepository_CreatePresign_Call {
return &MockRepository_CreatePresign_Call{Call: _e.mock.On("CreatePresign", ctx, draft)}
// - limits domain.AdmissionLimits
func (_e *MockRepository_Expecter) CreatePresign(ctx any, draft any, limits any) *MockRepository_CreatePresign_Call {
return &MockRepository_CreatePresign_Call{Call: _e.mock.On("CreatePresign", ctx, draft, limits)}
}
func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft)) *MockRepository_CreatePresign_Call {
func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits)) *MockRepository_CreatePresign_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -276,9 +277,14 @@ func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, d
if args[1] != nil {
arg1 = args[1].(domain.AttachmentDraft)
}
var arg2 domain.AdmissionLimits
if args[2] != nil {
arg2 = args[2].(domain.AdmissionLimits)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
@@ -289,14 +295,14 @@ func (_c *MockRepository_CreatePresign_Call) Return(attachment domain.Attachment
return _c
}
func (_c *MockRepository_CreatePresign_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)) *MockRepository_CreatePresign_Call {
func (_c *MockRepository_CreatePresign_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits) (domain.Attachment, error)) *MockRepository_CreatePresign_Call {
_c.Call.Return(run)
return _c
}
// CreateQueued provides a mock function for the type MockRepository
func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.AttachmentDraft, job domain.Job) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, job)
func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, job, limits)
if len(ret) == 0 {
panic("no return value specified for CreateQueued")
@@ -304,16 +310,16 @@ func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.Atta
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, job)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, job, limits)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, job)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, job, limits)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.Job) error); ok {
r1 = returnFunc(ctx, draft, job)
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) error); ok {
r1 = returnFunc(ctx, draft, job, limits)
} else {
r1 = ret.Error(1)
}
@@ -329,11 +335,12 @@ type MockRepository_CreateQueued_Call struct {
// - ctx context.Context
// - draft domain.AttachmentDraft
// - job domain.Job
func (_e *MockRepository_Expecter) CreateQueued(ctx any, draft any, job any) *MockRepository_CreateQueued_Call {
return &MockRepository_CreateQueued_Call{Call: _e.mock.On("CreateQueued", ctx, draft, job)}
// - limits domain.AdmissionLimits
func (_e *MockRepository_Expecter) CreateQueued(ctx any, draft any, job any, limits any) *MockRepository_CreateQueued_Call {
return &MockRepository_CreateQueued_Call{Call: _e.mock.On("CreateQueued", ctx, draft, job, limits)}
}
func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job)) *MockRepository_CreateQueued_Call {
func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits)) *MockRepository_CreateQueued_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -347,10 +354,15 @@ func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, dr
if args[2] != nil {
arg2 = args[2].(domain.Job)
}
var arg3 domain.AdmissionLimits
if args[3] != nil {
arg3 = args[3].(domain.AdmissionLimits)
}
run(
arg0,
arg1,
arg2,
arg3,
)
})
return _c
@@ -361,7 +373,7 @@ func (_c *MockRepository_CreateQueued_Call) Return(attachment domain.Attachment,
return _c
}
func (_c *MockRepository_CreateQueued_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job) (domain.Attachment, error)) *MockRepository_CreateQueued_Call {
func (_c *MockRepository_CreateQueued_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits) (domain.Attachment, error)) *MockRepository_CreateQueued_Call {
_c.Call.Return(run)
return _c
}
+36 -5
View File
@@ -52,8 +52,13 @@ type Repository interface {
ctx context.Context,
draft domain.AttachmentDraft,
job domain.Job,
limits domain.AdmissionLimits,
) (domain.Attachment, error)
CreatePresign(
ctx context.Context,
draft domain.AttachmentDraft,
limits domain.AdmissionLimits,
) (domain.Attachment, error)
CreatePresign(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)
CompletePresign(
ctx context.Context,
ownerID, attachmentID uuid.UUID,
@@ -191,6 +196,8 @@ func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachm
CreatedAt: time.Now().UTC(),
}
limits := s.admissionLimits()
created, err := s.repo.CreateQueued(ctx, domain.AttachmentDraft{
ID: id,
ChatID: input.ChatID,
@@ -203,10 +210,16 @@ func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachm
SHA256: sum,
Status: domain.AttachmentQueued,
PipelineVersion: s.config.PipelineVersion,
}, job)
}, job, limits)
if err != nil {
s.deleteObject(ctx, id, stagingKey)
if errors.Is(err, domain.ErrRateLimited) {
s.deleteObject(ctx, id, stagingKey)
return domain.Attachment{}, err
}
// An ambiguous COMMIT may have persisted the intent; leave the staging
// object for the sweeper instead of destroying a queued job's source.
return domain.Attachment{}, unavailable("commit attachment intent", err)
}
@@ -357,7 +370,7 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d
SHA256: request.SHA256,
Status: domain.AttachmentPending,
PipelineVersion: s.config.PipelineVersion,
}); err != nil {
}, s.admissionLimits()); err != nil {
return domain.PresignResult{}, err
}
@@ -511,7 +524,17 @@ func (s *Service) Complete(
s.config.PipelineVersion, s.config.MaxAttempts, jobID,
)
if err != nil {
s.deleteObject(ctx, id, verifiedKey)
// The verified key is shared by concurrent completions of this
// attachment. Never delete it here: a winning request may already have
// queued a job pointing at it. The orphan sweeper owns abandoned keys.
if errors.Is(err, domain.ErrConflict) {
current, getErr := s.repo.GetForOwner(ctx, ownerID, id)
if getErr == nil && current.SHA256 == requestSHA && current.Status.Public() {
return s.withVariants(ctx, current)
}
return domain.Attachment{}, fmt.Errorf("%w: attachment is no longer pending", domain.ErrConflict)
}
return domain.Attachment{}, unavailable("commit presigned attachment", err)
}
@@ -530,6 +553,14 @@ func (s *Service) Complete(
// verifyStaging checks the freshly written object; a mismatch is a broken
// staging handoff and must never become a 202.
func (s *Service) admissionLimits() domain.AdmissionLimits {
return domain.AdmissionLimits{
PerUser: s.config.MaxPendingPerUser,
Total: s.config.MaxPending,
Bytes: s.config.MaxStagedBytes,
}
}
func (s *Service) verifyStaging(ctx context.Context, key string, size int64, sum string) error {
head, err := s.store.Head(ctx, key)
if err != nil {
+84 -1
View File
@@ -189,7 +189,7 @@ func TestUploadStagesAndQueues(t *testing.T) {
}), mock.MatchedBy(func(job domain.Job) bool {
return job.PipelineVersion == 1 && job.Attempt == 1 &&
job.MaxAttempts == 5 && job.SourceKey != ""
})).Return(domain.Attachment{
}), domain.AdmissionLimits{}).Return(domain.Attachment{
ID: uuid.New(), ChatID: chatID, OwnerID: ownerID,
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentQueued, PipelineVersion: 1,
@@ -355,6 +355,89 @@ func TestCompleteQueuesPresignedObject(t *testing.T) {
require.Len(t, store.objects, 1)
}
func TestCompleteConcurrentConflictKeepsVerifiedSource(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
id := uuid.New()
chatID := uuid.New()
ownerID := uuid.New()
content := pngBytes(t, 10, 10)
sum := sha256.Sum256(content)
digest := hex.EncodeToString(sum[:])
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
store.objects[stagingKey] = storedObject{
data: content, contentType: "image/png",
metadata: map[string]string{"sha256": digest},
}
pending := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
StagingKey: stagingKey, ContentType: "image/png",
SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentPending, PipelineVersion: 1,
}
queued := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: "attachments/" + chatID.String() + "/" + id.String(),
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentQueued, PipelineVersion: 1,
}
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
repo.EXPECT().CompletePresign(
mock.Anything, ownerID, id, mock.Anything, mock.Anything,
1, 5, mock.Anything,
).Return(domain.Attachment{}, domain.ErrConflict).Once()
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(queued, nil).Once()
got, err := service.Complete(t.Context(), ownerID, id, digest)
require.NoError(t, err)
require.Equal(t, domain.AttachmentQueued, got.Status)
verified := 0
for key := range store.objects {
if strings.HasPrefix(key, "staging/verified/") {
verified++
}
}
require.Equal(t, 1, verified, "loser must not delete the winner's verified source")
}
func TestPresignHonoursAdmissionLimit(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().CreatePresign(mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{}, domain.ErrRateLimited).Once()
_, err := service.Presign(t.Context(), domain.PresignRequest{
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
ContentType: "image/png", SizeBytes: 10, SHA256: strings.Repeat("a", 64),
})
require.ErrorIs(t, err, domain.ErrRateLimited)
}
func TestUploadRateLimitedByAtomicAdmissionRemovesStaging(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), nil).Once()
repo.EXPECT().CreateQueued(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{}, domain.ErrRateLimited).Once()
_, err := service.Upload(t.Context(), attachment.UploadInput{
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(pngBytes(t, 8, 8)),
})
require.ErrorIs(t, err, domain.ErrRateLimited)
require.Empty(t, store.objects, "a rejected atomic admission must not leave staging")
}
func TestCompleteRejectsChecksumMismatch(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
@@ -1,245 +0,0 @@
package postgres
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type AttachmentRepository struct {
store *Store
}
func (r *AttachmentRepository) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
ChatID: chatID,
UserID: userID,
})
if err != nil {
return false, fmt.Errorf("check chat membership: %w", mapError(err))
}
return member, nil
}
func (r *AttachmentRepository) Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.CreateAttachment(ctx, sqlcgen.CreateAttachmentParams{
ID: draft.ID,
ChatID: draft.ChatID,
OwnerID: draft.OwnerID,
ObjectKey: draft.ObjectKey,
Filename: draft.Filename,
ContentType: draft.ContentType,
SizeBytes: draft.SizeBytes,
Sha256: draft.SHA256,
})
if err != nil {
return domain.Attachment{}, fmt.Errorf("create attachment: %w", mapError(err))
}
return mapCreateAttachment(row), nil
}
func (r *AttachmentRepository) MarkReady(
ctx context.Context,
id uuid.UUID,
objectKey string,
) (domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.MarkAttachmentReady(ctx, sqlcgen.MarkAttachmentReadyParams{
ID: id,
ObjectKey: objectKey,
})
if err != nil {
return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", mapError(err))
}
return mapMarkReadyAttachment(row), nil
}
func (r *AttachmentRepository) DeletePending(ctx context.Context, id uuid.UUID) error {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
if err := r.store.queries.DeletePendingAttachment(ctx, id); err != nil {
return fmt.Errorf("delete pending attachment: %w", mapError(err))
}
return nil
}
func (r *AttachmentRepository) GetForMember(
ctx context.Context,
userID, id uuid.UUID,
) (domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetAttachmentForMember(ctx, sqlcgen.GetAttachmentForMemberParams{
ID: id,
UserID: userID,
})
if err != nil {
return domain.Attachment{}, fmt.Errorf("get attachment for member: %w", mapError(err))
}
return mapMemberAttachment(row), nil
}
func (r *AttachmentRepository) GetForOwner(
ctx context.Context,
ownerID, id uuid.UUID,
) (domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetAttachmentForOwner(ctx, sqlcgen.GetAttachmentForOwnerParams{
ID: id,
OwnerID: ownerID,
})
if err != nil {
return domain.Attachment{}, fmt.Errorf("get attachment for owner: %w", mapError(err))
}
return mapOwnerAttachment(row), nil
}
func (r *AttachmentRepository) ListStates(
ctx context.Context,
chatID uuid.UUID,
ids []uuid.UUID,
) ([]domain.AttachmentState, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
rows, err := r.store.queries.ListAttachmentStatesForChat(ctx, sqlcgen.ListAttachmentStatesForChatParams{
ChatID: chatID,
Ids: ids,
})
if err != nil {
return nil, fmt.Errorf("list attachment states: %w", mapError(err))
}
states := make([]domain.AttachmentState, 0, len(rows))
for _, row := range rows {
states = append(states, domain.AttachmentState{
ID: row.ID,
Status: domain.AttachmentStatus(row.Status),
})
}
return states, nil
}
func (r *AttachmentRepository) ListStalePending(
ctx context.Context,
createdBefore time.Time,
limit int32,
) ([]domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
rows, err := r.store.queries.ListStalePendingAttachments(ctx, sqlcgen.ListStalePendingAttachmentsParams{
CreatedBefore: createdBefore,
RowLimit: limit,
})
if err != nil {
return nil, fmt.Errorf("list stale attachments: %w", mapError(err))
}
stale := make([]domain.Attachment, 0, len(rows))
for _, row := range rows {
stale = append(stale, mapStaleAttachment(row))
}
return stale, nil
}
func (r *AttachmentRepository) ListKeys(
ctx context.Context,
limit, offset int32,
) ([]domain.AttachmentKey, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
rows, err := r.store.queries.ListAttachmentKeys(ctx, sqlcgen.ListAttachmentKeysParams{
RowLimit: limit,
RowOffset: offset,
})
if err != nil {
return nil, fmt.Errorf("list attachment keys: %w", mapError(err))
}
keys := make([]domain.AttachmentKey, 0, len(rows))
for _, row := range rows {
keys = append(keys, domain.AttachmentKey{
ID: row.ID,
ObjectKey: row.ObjectKey,
Status: domain.AttachmentStatus(row.Status),
CreatedAt: toUTCTime(row.CreatedAt),
})
}
return keys, nil
}
func mapCreateAttachment(row sqlcgen.CreateAttachmentRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func mapMarkReadyAttachment(row sqlcgen.MarkAttachmentReadyRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func mapMemberAttachment(row sqlcgen.GetAttachmentForMemberRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func mapOwnerAttachment(row sqlcgen.GetAttachmentForOwnerRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func mapStaleAttachment(row sqlcgen.ListStalePendingAttachmentsRow) domain.Attachment {
return legacyAttachment(row.ID, row.ChatID, row.OwnerID, row.ObjectKey, row.Filename,
row.ContentType, row.SizeBytes, row.Sha256, row.Status, row.ErrorCode, row.CreatedAt, row.UpdatedAt)
}
func legacyAttachment(
id, chatID, ownerID uuid.UUID,
objectKey, filename, contentType string,
sizeBytes int64,
sha, status string,
errorCode pgtype.Text,
createdAt, updatedAt time.Time,
) domain.Attachment {
attachment := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: objectKey,
Filename: filename, ContentType: contentType, SizeBytes: sizeBytes,
SHA256: sha, Status: domain.AttachmentStatus(status),
PipelineVersion: 1, CreatedAt: createdAt, UpdatedAt: updatedAt,
}
if errorCode.Valid {
code := errorCode.String
attachment.ErrorCode = &code
}
return attachment
}
@@ -1,92 +0,0 @@
//go:build integration
package postgres_test
import (
"strings"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
)
type AttachmentRepositorySuite struct {
BaseSuite
}
func TestAttachmentRepositorySuite(t *testing.T) {
suite.Run(t, new(AttachmentRepositorySuite))
}
func (s *AttachmentRepositorySuite) TestLifecycleAndMessageLinks() {
alice := s.createUser("alice")
bob := s.createUser("bob")
eve := s.createUser("eve")
chat := s.createChat(alice, bob)
id, err := uuid.NewV7()
s.Require().NoError(err)
objectKey := "attachments/" + chat.ID.String() + "/" + id.String()
digest := strings.Repeat("a", 64)
created, err := s.store.Attachments().Create(s.T().Context(), domain.AttachmentDraft{
ID: id,
ChatID: chat.ID,
OwnerID: alice.ID,
ObjectKey: objectKey,
Filename: "photo.png",
ContentType: "image/png",
SizeBytes: 123,
SHA256: digest,
})
s.Require().NoError(err)
s.Equal(domain.AttachmentPending, created.Status)
visible, err := s.store.Attachments().GetForMember(s.T().Context(), bob.ID, id)
s.Require().NoError(err)
s.Equal(alice.ID, visible.OwnerID)
_, err = s.store.Attachments().GetForMember(s.T().Context(), eve.ID, id)
s.Require().ErrorIs(err, domain.ErrNotFound)
ready, err := s.store.Attachments().MarkReady(s.T().Context(), id, objectKey)
s.Require().NoError(err)
s.Equal(domain.AttachmentReady, ready.Status)
states, err := s.store.Attachments().ListStates(
s.T().Context(), chat.ID, []uuid.UUID{id},
)
s.Require().NoError(err)
s.Require().Len(states, 1)
s.Equal(domain.AttachmentReady, states[0].Status)
key := uuid.NewString()
draft := domain.MessageDraft{
ChatID: chat.ID,
SenderID: alice.ID,
Text: "",
AttachmentIDs: []uuid.UUID{id},
Idempotency: domain.MessageIdempotency{
Key: key,
RequestHash: [32]byte{1},
},
}
message, err := s.store.Messages().Create(s.T().Context(), draft)
s.Require().NoError(err)
s.Equal([]uuid.UUID{id}, message.AttachmentIDs)
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, bob.ID, nil, 50)
s.Require().NoError(err)
s.Require().Len(page.Items, 1)
s.Equal([]uuid.UUID{id}, page.Items[0].AttachmentIDs)
s.Empty(page.Items[0].Text)
replayed, err := s.store.Messages().Create(s.T().Context(), draft)
s.Require().NoError(err)
s.Equal(message.ID, replayed.ID)
s.Equal([]uuid.UUID{id}, replayed.AttachmentIDs)
}
+148 -22
View File
@@ -64,6 +64,8 @@ func scanAttachmentRow(row rowScanner) (domain.Attachment, error) {
}
attachment.Status = domain.AttachmentStatus(status)
attachment.CreatedAt = toUTCTime(attachment.CreatedAt)
attachment.UpdatedAt = toUTCTime(attachment.UpdatedAt)
if errCode.Valid {
code := errCode.String
attachment.ErrorCode = &code
@@ -112,6 +114,9 @@ func scanJobRow(row rowScanner) (domain.Job, error) {
}
job.Status = domain.JobStatus(status)
job.AvailableAt = toUTCTime(job.AvailableAt)
job.CreatedAt = toUTCTime(job.CreatedAt)
job.UpdatedAt = toUTCTime(job.UpdatedAt)
if owner.Valid {
job.LeaseOwner = owner.String
}
@@ -330,12 +335,11 @@ func (r *PipelineRepository) Admission(
err = r.store.pool.QueryRow(ctx, `
SELECT
count(*) FILTER (WHERE a.owner_id = $1)::int,
count(*) FILTER (WHERE owner_id = $1)::int,
count(*)::int,
COALESCE(sum(a.size_bytes), 0)::bigint
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.status IN ('queued', 'processing')`, ownerID).Scan(
COALESCE(sum(size_bytes), 0)::bigint
FROM attachments
WHERE status IN ('pending', 'queued', 'processing')`, ownerID).Scan(
&userPending, &totalPending, &stagedBytes,
)
if err != nil {
@@ -394,10 +398,15 @@ func (r *PipelineRepository) CreateQueued(
ctx context.Context,
draft domain.AttachmentDraft,
job domain.Job,
limits domain.AdmissionLimits,
) (domain.Attachment, error) {
var created domain.Attachment
err := r.withTx(ctx, func(tx pgx.Tx) error {
if err := checkAdmissionTx(ctx, tx, draft.OwnerID, limits); err != nil {
return err
}
row := tx.QueryRow(ctx, `
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type,
@@ -1307,6 +1316,15 @@ func (r *PipelineRepository) Reprocess(
var created domain.Job
err := r.withTx(ctx, func(tx pgx.Tx) error {
// Keep the global lock order job -> attachment, as in CompleteJob.
if _, err := tx.Exec(ctx, `
SELECT 1 FROM attachment_jobs
WHERE attachment_id = $1 AND status IN ('queued', 'processing')
AND pipeline_version < $2
FOR UPDATE`, attachmentID, targetVersion); err != nil {
return fmt.Errorf("lock superseded jobs: %w", mapError(err))
}
attachmentRow := tx.QueryRow(ctx, `
SELECT `+attachmentReturning+`
FROM attachments WHERE id = $1 FOR UPDATE`, attachmentID)
@@ -1320,9 +1338,9 @@ func (r *PipelineRepository) Reprocess(
return fmt.Errorf("%w: target pipeline version must be newer", domain.ErrConflict)
}
sourceKey := attachment.StagingKey
sourceKey := attachment.ObjectKey
if sourceKey == "" {
sourceKey = attachment.ObjectKey
sourceKey = attachment.StagingKey
}
if sourceKey == "" {
return fmt.Errorf("%w: attachment has no source object", domain.ErrConflict)
@@ -1394,6 +1412,10 @@ func (r *PipelineRepository) ReplayJob(
jobID uuid.UUID,
extraAttempts int,
) (domain.Job, error) {
if extraAttempts < 1 {
return domain.Job{}, fmt.Errorf("%w: replay attempts must be >= 1", domain.ErrValidation)
}
var replayed domain.Job
err := r.withTx(ctx, func(tx pgx.Tx) error {
@@ -1629,7 +1651,7 @@ func (r *PipelineRepository) ListReferencedKeys(
SELECT object_key AS key FROM attachment_variants
UNION
SELECT staging_key AS key FROM attachments
WHERE staging_key IS NOT NULL AND status IN ('queued', 'processing')
WHERE staging_key IS NOT NULL AND status IN ('queued', 'processing', 'failed')
) referenced
WHERE key > $1
ORDER BY key
@@ -1776,30 +1798,89 @@ func (r *PipelineRepository) InsertRawOutbox(
func (r *PipelineRepository) CreatePresign(
ctx context.Context,
draft domain.AttachmentDraft,
limits domain.AdmissionLimits,
) (domain.Attachment, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
var attachment domain.Attachment
row := r.store.pool.QueryRow(ctx, `
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type,
size_bytes, sha256, status, pipeline_version, staging_key
err := r.withTx(ctx, func(tx pgx.Tx) error {
if err := checkAdmissionTx(ctx, tx, draft.OwnerID, limits); err != nil {
return err
}
row := tx.QueryRow(ctx, `
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type,
size_bytes, sha256, status, pipeline_version, staging_key
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', $9, $10)
RETURNING `+attachmentReturning,
draft.ID, draft.ChatID, draft.OwnerID, draft.ObjectKey, draft.Filename,
draft.ContentType, draft.SizeBytes, draft.SHA256,
draft.PipelineVersion, draft.StagingKey,
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', $9, $10)
RETURNING `+attachmentReturning,
draft.ID, draft.ChatID, draft.OwnerID, draft.ObjectKey, draft.Filename,
draft.ContentType, draft.SizeBytes, draft.SHA256,
draft.PipelineVersion, draft.StagingKey,
)
attachment, err := scanAttachmentRow(row)
created, err := scanAttachmentRow(row)
if err != nil {
return fmt.Errorf("create presign attachment: %w", mapError(err))
}
attachment = created
return nil
})
if err != nil {
return domain.Attachment{}, fmt.Errorf("create presign attachment: %w", mapError(err))
return domain.Attachment{}, err
}
return attachment, nil
}
const admissionLockKey int64 = 0x41444d31 // "ADM1"
// checkAdmissionTx serializes upload admission across API replicas with a
// transaction-scoped advisory lock, then re-counts pending/queued/processing
// rows. This closes the check-then-act window before the row is inserted.
func checkAdmissionTx(ctx context.Context, tx pgx.Tx, ownerID uuid.UUID, limits domain.AdmissionLimits) error {
if limits.PerUser == 0 && limits.Total == 0 && limits.Bytes == 0 {
return nil
}
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, admissionLockKey); err != nil {
return fmt.Errorf("lock admission: %w", mapError(err))
}
var (
total int
bytes int64
)
err := tx.QueryRow(ctx, `
SELECT count(*)::int, COALESCE(sum(size_bytes), 0)::bigint
FROM attachments
WHERE status IN ('pending', 'queued', 'processing')`).Scan(&total, &bytes)
if err != nil {
return fmt.Errorf("admission count: %w", mapError(err))
}
perUser := 0
if limits.PerUser > 0 {
if err := tx.QueryRow(ctx, `
SELECT count(*)::int FROM attachments
WHERE status IN ('pending', 'queued', 'processing')
AND owner_id = $1`, ownerID).Scan(&perUser); err != nil {
return fmt.Errorf("admission per-user count: %w", mapError(err))
}
}
if (limits.PerUser > 0 && perUser >= limits.PerUser) ||
(limits.Total > 0 && total >= limits.Total) ||
(limits.Bytes > 0 && bytes >= limits.Bytes) {
return fmt.Errorf("%w: admission limit reached", domain.ErrRateLimited)
}
return nil
}
// DuplicateJob publishes another copy of a specific job attempt. It is used by
// the fault-injection evidence to simulate duplicate delivery of an old version.
func (r *PipelineRepository) DuplicateJob(ctx context.Context, jobID uuid.UUID) (domain.OutboxMessage, error) {
@@ -1832,3 +1913,48 @@ func (r *PipelineRepository) DuplicateJob(ctx context.Context, jobID uuid.UUID)
return created, nil
}
// ReconcileQueuedJobs republishes jobs whose only broker delivery was lost
// (dead-lettered, dropped, or a broker data loss). The worker CAS makes an
// extra delivery a no-op. Only one unpublished outbox row is created per job.
func (r *PipelineRepository) ReconcileQueuedJobs(
ctx context.Context,
olderThan time.Duration,
limit int,
) (int, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
tag, err := r.store.pool.Exec(ctx, `
WITH lost AS (
SELECT j.job_id, j.attachment_id, j.pipeline_version, j.attempt, j.created_at
FROM attachment_jobs j
WHERE j.status = 'queued'
AND j.available_at < now() - $1::interval
AND NOT EXISTS (
SELECT 1 FROM outbox_messages o
WHERE o.job_id = j.job_id AND o.published_at IS NULL
)
ORDER BY j.available_at
LIMIT $2
FOR UPDATE SKIP LOCKED
)
INSERT INTO outbox_messages (job_id, attempt, kind, routing_key, payload, available_at)
SELECT job_id, attempt, 'reconcile', $3,
jsonb_build_object(
'schema_version', 1,
'job_id', job_id,
'type', $3::text,
'attachment_id', attachment_id,
'pipeline_version', pipeline_version,
'attempt', attempt,
'created_at', created_at),
now()
FROM lost`,
intervalString(olderThan), limit, defaultRoutingKey)
if err != nil {
return 0, fmt.Errorf("reconcile queued jobs: %w", mapError(err))
}
return int(tag.RowsAffected()), nil
}
@@ -64,7 +64,7 @@ func (s *PipelineSuite) TestCreateClaimCompleteAndIdempotentRedelivery() {
draft, job := s.attachmentDraft(chat, alice, 1)
repo := s.store.Pipeline()
created, err := repo.CreateQueued(s.T().Context(), draft, job)
created, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
s.Equal(domain.AttachmentQueued, created.Status)
s.Equal(1, created.PipelineVersion)
@@ -114,7 +114,7 @@ func (s *PipelineSuite) TestLeaseExpiryIsBoundedByMaxAttempts() {
job.MaxAttempts = 1
repo := s.store.Pipeline()
_, err := repo.CreateQueued(s.T().Context(), draft, job)
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease", time.Millisecond)
@@ -133,3 +133,74 @@ func (s *PipelineSuite) TestLeaseExpiryIsBoundedByMaxAttempts() {
s.NotNil(dead.LastErrorCode)
s.Equal("retry_exhausted", *dead.LastErrorCode)
}
func (s *PipelineSuite) TestAdmissionCountsPendingPresignAndIsAtomic() {
alice := s.createUser("alice")
chat := s.createChat(alice)
repo := s.store.Pipeline()
draft, _ := s.attachmentDraft(chat, alice, 1)
draft.ObjectKey = "staging/presign/" + chat.ID.String() + "/" + draft.ID.String()
draft.StagingKey = draft.ObjectKey
draft.Status = domain.AttachmentPending
limits := domain.AdmissionLimits{PerUser: 1, Total: 10}
_, err := repo.CreatePresign(s.T().Context(), draft, limits)
s.Require().NoError(err)
second, _ := s.attachmentDraft(chat, alice, 1)
second.ObjectKey = "staging/presign/" + chat.ID.String() + "/" + second.ID.String()
second.StagingKey = second.ObjectKey
second.Status = domain.AttachmentPending
_, err = repo.CreatePresign(s.T().Context(), second, limits)
s.Require().ErrorIs(err, domain.ErrRateLimited)
}
func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() {
alice := s.createUser("alice")
chat := s.createChat(alice)
repo := s.store.Pipeline()
draft, job := s.attachmentDraft(chat, alice, 1)
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
claimed, err := repo.ClaimOutbox(s.T().Context(), "relay", time.Minute, 10)
s.Require().NoError(err)
s.Require().Len(claimed, 1)
s.Require().NoError(repo.MarkPublished(s.T().Context(), []int64{claimed[0].ID}))
reconciled, err := repo.ReconcileQueuedJobs(s.T().Context(), 0, 10)
s.Require().NoError(err)
s.Equal(1, reconciled)
pending, err := repo.ClaimOutbox(s.T().Context(), "relay", time.Minute, 10)
s.Require().NoError(err)
s.Require().Len(pending, 1)
s.Equal("reconcile", pending[0].Kind)
s.Equal(job.ID, pending[0].JobID)
}
func (s *PipelineSuite) TestFailedStagingStaysReferencedUntilRetention() {
alice := s.createUser("alice")
chat := s.createChat(alice)
repo := s.store.Pipeline()
draft, job := s.attachmentDraft(chat, alice, 1)
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
ok, err := repo.FailJob(s.T().Context(), job.ID, 1, "lease", "invalid_image")
s.Require().NoError(err)
s.True(ok)
keys, err := repo.ListReferencedKeys(s.T().Context(), "", 100)
s.Require().NoError(err)
s.Contains(keys, draft.StagingKey)
}
+5 -9
View File
@@ -17,12 +17,11 @@ type Store struct {
queryTimeout time.Duration
idempotencyTTL time.Duration
users *UserRepository
chats *ChatRepository
messages *MessageRepository
sessions *SessionRepository
attachments *AttachmentRepository
pipeline *PipelineRepository
users *UserRepository
chats *ChatRepository
messages *MessageRepository
sessions *SessionRepository
pipeline *PipelineRepository
}
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration) (*Store, error) {
@@ -67,7 +66,6 @@ func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration)
store.chats = &ChatRepository{store: store}
store.messages = &MessageRepository{store: store}
store.sessions = &SessionRepository{store: store}
store.attachments = &AttachmentRepository{store: store}
store.pipeline = &PipelineRepository{store: store}
return store, nil
@@ -81,8 +79,6 @@ func (s *Store) Messages() *MessageRepository { return s.messages }
func (s *Store) Sessions() *SessionRepository { return s.sessions }
func (s *Store) Attachments() *AttachmentRepository { return s.attachments }
func (s *Store) Pipeline() *PipelineRepository { return s.pipeline }
func (s *Store) Ping(ctx context.Context) error {
+8 -1
View File
@@ -225,7 +225,14 @@ func (w *Worker) process(
return
case <-ticker.C:
ok, err := w.repo.Heartbeat(jobCtx, job.ID, job.Attempt, w.config.Owner, w.config.LeaseTTL)
if err != nil || !ok {
if err != nil {
// A DB blip is not proof that the lease is gone. Keep trying;
// the fencing CAS still prevents a stale commit.
w.log.WarnContext(jobCtx, "heartbeat failed", slog.Any("error", err))
continue
}
if !ok {
leaseLost = true
cancel()
+3 -2
View File
@@ -77,7 +77,7 @@ wait_readiness() {
}
up_slots() {
curl -s --noproxy '*' "$STATS" | awk -F, '$1 ~ /^api/ && $18 == "UP" && $2 != "BACKEND" { printf "%s ", $2 }'
curl -s --noproxy '*' "$STATS" | awk -F, '$1 ~ /^api/ && $18 ~ /^UP/ && $2 != "BACKEND" { printf "%s ", $2 }'
}
wait_new_up_slot() {
@@ -175,7 +175,8 @@ wait_slot_status() {
if wait_slot_status "$slot" DOWN; then
echo " $slot went DOWN ${SWAIT_SECONDS}s after its database was cut (check: inter 2s fall 2)"
else
echo " WARNING: $slot is still not DOWN" >&2
echo " FAIL: $slot is still not DOWN" >&2
exit 1
fi
echo " stats after failure: $(stats)"
+16 -1
View File
@@ -17,6 +17,17 @@ from tests_helpers import ROOT, compose, psql # noqa: E402
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
def wait_api_ready(client, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
client.call('GET', '/health/ready', schema='Health')
return
except Failure:
time.sleep(0.2)
raise Failure('API did not become ready after restart')
def wait_state(client, actor, attachment, expected, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
@@ -46,7 +57,10 @@ def main():
time.sleep(2)
still = client.call('GET', '/api/v1/attachments/' + attached['id'], actor=alice, schema='Attachment')['json']
check(still['status'] == 'queued', 'worker stopped but job was processed synchronously')
print('worker down: 202 queued, content 409, queued attachment linked')
# The README demo restarts the API after the 202 and before the worker.
compose('restart', 'api')
wait_api_ready(client)
print('worker down: 202 queued, content 409, queued attachment linked, API restarted')
finally:
compose('up', '-d', '--no-deps', 'worker', check=False)
@@ -76,6 +90,7 @@ def main():
# 3. A full stack restart with volumes keeps ready data and the worker path.
compose('restart', 'api', 'worker', 'relay')
wait_api_ready(client)
recovered = client.call('GET', '/api/v1/attachments/' + ready['id'], actor=bob, schema='Attachment')['json']
check(recovered['status'] == 'ready', 'ready attachment lost across restart')
body = client.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)
+10 -1
View File
@@ -110,6 +110,8 @@ def scenario_transient_exhaustion(client, alice, chat):
attached, _ = client.attachment(alice, chat)
jid = job_id(attached['id'])
dlq_before = queue_messages('attachment.process.dead')
worker_with(
FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_FAIL='transient',
PROCESSING_RETRY_BASE='100ms', PROCESSING_RETRY_CAP='500ms',
@@ -120,7 +122,14 @@ def scenario_transient_exhaustion(client, alice, chat):
events = psql("select event || ':' || coalesce(attempt,0) from attachment_job_events where job_id='%s' order by id" % jid)
check(events.count('retried:') == 4, 'expected four managed retries: ' + events)
check(events.count('failed:') == 1, 'expected one terminal failure: ' + events)
check(queue_messages('attachment.process.dead') >= 1, 'terminal failure did not reach the DLQ')
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
if queue_messages('attachment.process.dead') >= dlq_before + 1:
break
time.sleep(0.2)
check(queue_messages('attachment.process.dead') >= dlq_before + 1,
'terminal failure did not add a DLQ message')
print('transient exhaustion: attempts=5, retry_exhausted, four retries, DLQ message present')
reset_worker()