Compare commits

..
1 Commits
Author SHA1 Message Date
Vladislav Kunetskiy 01b885e846 lab5: очереди и асинхронная обработка изображений
Durable staging handoff, transactional outbox, at-least-once worker with lease fencing, idempotent versioned pipeline, three variants, operator tooling, contract tests and evidence. Includes the review fixes: reprocess source selection and failure settlement, replay guards, stale-job retirement, PNG structural/raster validation, migration rollback safety and audit events.
2026-10-31 14:34:24 +03:00
15 changed files with 125 additions and 53 deletions
+2 -2
View File
@@ -110,7 +110,7 @@ flowchart LR
| Полный restart стека | `lab5_async.py` | ready-вложение и original сохранились | `evidence/lab5/async.txt` |
| Варианты: thumbnail/crop/optimized | `make test-queue`/`lab5_variants.py` | thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized WebP 320×200; metadata == bytes; EXIF отсутствует | `evidence/lab5/variants.txt` |
| Состояния queued/processing/ready/failed | `lab5_async.py`, `lab5_faults.py` | queued/ready и failed/error_code наблюдаются через API | `evidence/lab5/async.txt`, `faults.txt` |
| 415 на невалидное изображение | `make test-attachments` | пустое тело, IDAT-CRC, MIME spoof, не-zlib IDAT, пустой растр, недопустимый scanline-фильтр, несовместимые color type/bit depth, дубликаты IHDR, мусор после zlib, битый tRNS, PLTE сверх bit depth — 415 до 202 | `evidence/lab5/attachments-negative.txt` |
| 415 на невалидное изображение | `make test-attachments` | пустое тело, IDAT-CRC, MIME spoof, не-zlib IDAT, пустой растр, недопустимый scanline-фильтр, несовместимые color type/bit depth, дубликаты IHDR, мусор после zlib, битый tRNS, PLTE сверх bit depth, tRNS сверх PLTE — 415 до 202 | `evidence/lab5/attachments-negative.txt` |
| Original неизменен | smoke + variants | скачанные байты и sha совпадают с загруженными | `evidence/lab5/smoke.txt`, `variants.txt` |
| Retry/backoff/classification | `make test-faults` | permanent → failed сразу; transient → 5 attempts, 4 retry events, `retry_exhausted`; DLQ | `evidence/lab5/faults.txt` |
| DLQ/registry + replay | `lab5_faults.py` | failed виден в `jobctl failed`; replay → ready; replay ready refused | `evidence/lab5/faults.txt` |
@@ -149,7 +149,7 @@ flowchart LR
| Transient errors | 5 attempts, backoff+jitter, failed | attempts=5, `retry_exhausted`, DLQ |
| Failed replay | failed→queued→ready без дубля | ready, один thumbnail |
| v1 ready → reprocess v2 → old v1 delivery | v2 не перезаписывается | pv=2, variants v2, stale v1 ack |
| Reprocess queued при остановленном worker | v2 берёт проверенный staging, а не несуществующий original | pv=2 ready, v1 superseded, v2 ready |
| Reprocess queued при остановленном worker | v2 берёт проверенный staging, а не несуществующий original | pv=2 ready, v1 superseded, событие superseded записано |
| Reprocess v2 падает до публикации | вложение терминально failed, не вечный queued | failed/error_code, active jobs 0 |
| Replay упавшей v2 до публикации | API не показывает stale failed, работа возвращается | job queued, attachment queued, затем ready:v2 |
| Replay старой failed-v1 при наличии v2 | команда отклонена, источник v2 не потерян | v1 failed, v2 queued → ready:v2 |
+2 -2
View File
@@ -1,11 +1,11 @@
# make test-queue 2026-10-30T22:43:35Z
# make test-queue 2026-10-31T11:26: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/lab5_async.py --base-url "http://localhost:8080"
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
stack restart: ready attachment and original preserved
worker down: reprocess pipeline 2 accepted, upload still queued
worker down: reprocess pipeline 2 accepted, v1 audit event recorded, upload still queued
worker up: reprocessed upload reached ready at pipeline 2, v1 superseded
worker down: reprocess pipeline 3 refused, v1 job untouched
worker up: preserved upload reached ready at pipeline 1
+2 -1
View File
@@ -1,4 +1,4 @@
# make test-attachments 2026-10-30T22:43:33Z
# make test-attachments 2026-10-31T11:26:14Z
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
@@ -13,6 +13,7 @@ trailing bytes after PNG zlib stream: 415
tRNS on RGBA PNG: 415
short tRNS on RGB PNG: 415
PLTE entries exceed palette bit depth: 415
palette tRNS exceeds PLTE entries: 415
dangerous filenames: 400
foreign attachment metadata/content: 404
empty text without attachments: 400
+1 -1
View File
@@ -1,4 +1,4 @@
# make test-faults 2026-10-30T22:43:58Z
# make test-faults 2026-10-31T11:27: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 student-tests/lab5_faults.py --base-url "http://localhost:8080"
permanent failure: failed/injected_failure, content 409, failed attachment not linkable, registry visible
replay: failed -> queued -> ready, one thumbnail
+2 -2
View File
@@ -1,2 +1,2 @@
ok mtusi-messenger/internal/storage/postgres 9.740s
ok mtusi-messenger/internal/storage/redis 1.237s
ok mtusi-messenger/internal/storage/postgres 9.448s
ok mtusi-messenger/internal/storage/redis 1.238s
+9 -9
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 7.230292ms: 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 6.264542ms: 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 (deps|exports_file|files|imports|name|compiled_files|types_sizes) took 285.717958ms"
level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 10.492667ms"
level=info msg="[linters_context/goanalysis] analyzers took 21.264339055s with top 10 stages: goimports: 5.91549475s, revive: 3.740582125s, gosec: 1.775157082s, unparam: 1.224420001s, wastedassign: 868.611793ms, buildir: 477.238122ms, buildssa: 376.629332ms, nilness: 292.332672ms, sloglint: 234.71729ms, gofumpt: 218.928999ms"
level=info msg="[loader] Go packages loading at mode 8767 (compiled_files|deps|exports_file|files|types_sizes|imports|name) took 193.808375ms"
level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 11.667ms"
level=info msg="[linters_context/goanalysis] analyzers took 0s with no stages"
level=info msg="[runner/exclusion_rules] Skipped 14 issues by rules: [Path: \"_test\\\\.go\", Linters: \"gosec, prealloc, forcetypeassert, unparam\"]"
level=info msg="[runner] Issues before processing: 887, after processing: 0"
level=info msg="[runner] Processors filtering stat (in/out): path_absoluter: 887/887, cgo: 887/887, filename_unadjuster: 887/887, generated_file_filter: 887/298, exclusion_paths: 887/887, invalid_issue: 887/887, path_relativity: 887/887, exclusion_rules: 298/6, nolint_filter: 6/0"
level=info msg="[runner] processing took 2.876665ms with stages: generated_file_filter: 1.76725ms, nolint_filter: 552.542µs, path_relativity: 268.125µs, exclusion_rules: 249.625µs, invalid_issue: 13.541µs, cgo: 12.251µs, path_absoluter: 6.125µs, sort_results: 2.875µs, filename_unadjuster: 2.792µs, max_same_issues: 333ns, fixer: 291ns, path_shortener: 249ns, max_per_file_from_linter: 209ns, exclusion_paths: 208ns, path_prettifier: 166ns, diff: 42ns, uniq_by_line: 41ns, max_from_linter: 0s, source_code: 0s, severity-rules: 0s"
level=info msg="[runner] linters took 2.891797125s with stages: goanalysis_metalinter: 2.888879125s"
level=info msg="[runner] Processors filtering stat (in/out): path_absoluter: 887/887, cgo: 887/887, filename_unadjuster: 887/887, nolint_filter: 6/0, invalid_issue: 887/887, exclusion_paths: 887/887, path_relativity: 887/887, generated_file_filter: 887/298, exclusion_rules: 298/6"
level=info msg="[runner] processing took 2.828168ms with stages: generated_file_filter: 1.490334ms, nolint_filter: 764.209µs, path_relativity: 284.917µs, exclusion_rules: 251.001µs, invalid_issue: 13.417µs, cgo: 12.25µs, path_absoluter: 4.666µs, sort_results: 2.916µs, filename_unadjuster: 2.542µs, max_same_issues: 874ns, diff: 167ns, fixer: 166ns, path_prettifier: 125ns, max_per_file_from_linter: 125ns, exclusion_paths: 125ns, path_shortener: 124ns, uniq_by_line: 84ns, severity-rules: 42ns, max_from_linter: 42ns, source_code: 42ns"
level=info msg="[runner] linters took 629.148708ms with stages: goanalysis_metalinter: 626.277292ms"
0 issues.
level=info msg="File cache stats: 0 entries of total size 0B"
level=info msg="Memory: 33 samples, avg is 393.4MB, max is 704.0MB"
level=info msg="Execution took 3.196263875s"
level=info msg="Memory: 10 samples, avg is 87.2MB, max is 111.5MB"
level=info msg="Execution took 841.622625ms"
+1 -1
View File
@@ -1,3 +1,3 @@
# make test 2026-10-30T22:43:54Z
# make test 2026-10-31T11:26:59Z
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.
+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 2.864s
ok mtusi-messenger/internal/domain 2.165s
ok mtusi-messenger/internal/config 1.717s
ok mtusi-messenger/internal/domain 2.647s
? mtusi-messenger/internal/failpoint [no test files]
ok mtusi-messenger/internal/health 3.964s
ok mtusi-messenger/internal/imagecheck 1.632s
ok mtusi-messenger/internal/imageproc 1.734s
ok mtusi-messenger/internal/logger 3.393s
ok mtusi-messenger/internal/health 1.315s
ok mtusi-messenger/internal/imagecheck 3.766s
ok mtusi-messenger/internal/imageproc 2.400s
ok mtusi-messenger/internal/logger 2.338s
? mtusi-messenger/internal/outbox [no test files]
ok mtusi-messenger/internal/platform/cache 2.618s
ok mtusi-messenger/internal/platform/cache 4.909s
? mtusi-messenger/internal/platform/cache/mocks [no test files]
ok mtusi-messenger/internal/platform/objectstore 3.077s
ok mtusi-messenger/internal/platform/password 2.238s
ok mtusi-messenger/internal/platform/token 4.261s
ok mtusi-messenger/internal/service/attachment 5.207s
ok mtusi-messenger/internal/platform/objectstore 6.507s
ok mtusi-messenger/internal/platform/password 3.349s
ok mtusi-messenger/internal/platform/token 3.304s
ok mtusi-messenger/internal/service/attachment 5.105s
? mtusi-messenger/internal/service/attachment/mocks [no test files]
ok mtusi-messenger/internal/service/chat 4.889s
ok mtusi-messenger/internal/service/chat 4.460s
? mtusi-messenger/internal/service/chat/mocks [no test files]
ok mtusi-messenger/internal/service/message 5.511s
ok mtusi-messenger/internal/service/message 4.119s
? mtusi-messenger/internal/service/message/mocks [no test files]
ok mtusi-messenger/internal/service/session 4.899s
ok mtusi-messenger/internal/service/session 5.771s
? mtusi-messenger/internal/service/session/mocks [no test files]
ok mtusi-messenger/internal/service/user 3.864s
ok mtusi-messenger/internal/service/user 6.251s
? mtusi-messenger/internal/service/user/mocks [no test files]
ok mtusi-messenger/internal/storage/postgres 5.476s
ok mtusi-messenger/internal/storage/postgres 6.484s
? 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 5.863s
ok mtusi-messenger/internal/transport/rest 6.893s
? 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]
+23 -13
View File
@@ -77,19 +77,20 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
}
var (
info Info
seen = make(map[string]bool, 4)
first = true
hasIDAT bool
paletteReady bool
trnsSeen bool
colorType byte
bitDepth byte
idat bytes.Buffer
raster []pngPass
rasterBytes int64
maxIDAT int64 = -1
lastChunk string
info Info
seen = make(map[string]bool, 4)
first = true
hasIDAT bool
paletteReady bool
trnsSeen bool
colorType byte
bitDepth byte
paletteEntries int
idat bytes.Buffer
raster []pngPass
rasterBytes int64
maxIDAT int64 = -1
lastChunk string
)
info.ContentType = "image/png"
@@ -214,6 +215,8 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
return Info{}, corruptf("png PLTE chunk after tRNS")
}
paletteEntries = int(length / 3)
if !hasIDAT {
paletteReady = true
}
@@ -243,6 +246,13 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
if length > 256 {
return Info{}, corruptf("png tRNS length %d", length)
}
if int(length) > paletteEntries {
return Info{}, corruptf(
"png tRNS length %d exceeds %d palette entries",
length, paletteEntries,
)
}
default:
return Info{}, corruptf("png tRNS invalid for color type %d", colorType)
}
+7
View File
@@ -362,6 +362,13 @@ func TestValidateRejectsInvalidTRNS(t *testing.T) {
paletted,
pngChunk("IEND", nil),
),
"palette tRNS longer than PLTE": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 3, 0)),
pngChunk("PLTE", []byte{255, 0, 0}),
pngChunk("tRNS", []byte{0, 0}),
paletted,
pngChunk("IEND", nil),
),
"duplicate tRNS": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
pngChunk("tRNS", make([]byte, 6)),
@@ -142,9 +142,9 @@ ALTER TABLE attachments ADD CONSTRAINT attachments_error_consistency CHECK (
(status = 'ready' AND error_code IS NULL) OR
(status = 'failed' AND error_code IS NOT NULL) OR
status = 'pending'
);
) NOT VALID;
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (
status IN ('pending', 'ready', 'failed')
);
) NOT VALID;
@@ -1386,15 +1386,48 @@ func (r *PipelineRepository) Reprocess(
return fmt.Errorf("%w: attachment has no source object", domain.ErrConflict)
}
_, err = tx.Exec(ctx, `
rows, err := tx.Query(ctx, `
UPDATE attachment_jobs
SET status = 'superseded', updated_at = now(), completed_at = now()
WHERE attachment_id = $1 AND status IN ('queued', 'processing')
AND pipeline_version < $2`, attachmentID, targetVersion)
AND pipeline_version < $2
RETURNING job_id, attempt`, attachmentID, targetVersion)
if err != nil {
return fmt.Errorf("supersede old jobs: %w", mapError(err))
}
type supersededJob struct {
id uuid.UUID
attempt int
}
superseded := make([]supersededJob, 0, 2)
for rows.Next() {
var old supersededJob
if err := rows.Scan(&old.id, &old.attempt); err != nil {
rows.Close()
return fmt.Errorf("scan superseded job: %w", mapError(err))
}
superseded = append(superseded, old)
}
if err := rows.Err(); err != nil {
rows.Close()
return fmt.Errorf("list superseded jobs: %w", mapError(err))
}
rows.Close()
for _, old := range superseded {
if err := insertEventTx(ctx, tx, old.id, domain.EventSuperseded, old.attempt, ""); err != nil {
return err
}
}
if attachment.Status != domain.AttachmentReady {
_, err = tx.Exec(ctx, `
UPDATE attachments
@@ -495,6 +495,13 @@ func (s *PipelineSuite) TestClaimRetiresVersionStaleQueuedJob() {
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
`SELECT status FROM attachment_jobs WHERE job_id = $1`, job.ID).Scan(&status))
s.Equal(string(domain.JobSuperseded), status)
var supersededEvents int
s.Require().NoError(s.pool.QueryRow(s.T().Context(), `
SELECT count(*) FROM attachment_job_events
WHERE job_id = $1 AND event = $2`,
job.ID, string(domain.EventSuperseded)).Scan(&supersededEvents))
s.Equal(2, supersededEvents)
}
func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() {
+12
View File
@@ -145,6 +145,18 @@ def main():
upload(client, alice, chat, palette_overflow, expected=415)
print('PLTE entries exceed palette bit depth: 415')
# Palette transparency cannot describe more entries than PLTE provides.
palette_trns = crafted_png_extra(
1, 1, b'\x00\x00',
pre_idat=(
png_chunk(b'PLTE', bytes((255, 0, 0))),
png_chunk(b'tRNS', b'\x00\x00'),
),
bit_depth=8, color_type=3,
)
upload(client, alice, chat, palette_trns, expected=415)
print('palette tRNS exceeds PLTE entries: 415')
# Dangerous display names.
for name in ('../x.png', 'a/b.png', 'a\\b.png', 'a\x00.png', 'a\n.png'):
upload(client, alice, chat, fixture, filename=name, expected=400)
+3 -1
View File
@@ -109,7 +109,9 @@ def main():
check('SourceKey' in result.stdout, 'reprocess did not return the created job')
queued2 = client.call('GET', '/api/v1/attachments/' + pinned['id'], actor=alice, schema='Attachment')['json']
check(queued2['status'] == 'queued', 'reprocessed upload is not queued')
print('worker down: reprocess pipeline 2 accepted, upload still queued')
check(psql("select count(*) from attachment_job_events e join attachment_jobs j on j.job_id=e.job_id where j.attachment_id='%s' and j.pipeline_version=1 and e.event='superseded'" % pinned['id']) == '1',
'reprocess did not record the v1 superseded event')
print('worker down: reprocess pipeline 2 accepted, v1 audit event recorded, upload still queued')
finally:
compose('up', '-d', '--no-deps', 'worker', check=False)