diff --git a/scripts/lease-expiry.bat b/scripts/lease-expiry.bat new file mode 100644 index 00000000..f707ece5 --- /dev/null +++ b/scripts/lease-expiry.bat @@ -0,0 +1,113 @@ +@echo off +setlocal EnableDelayedExpansion +cd /d "%~dp0.." + +set BASE=http://localhost:8080 +set PASS=Example-only-not-a-real-secret-123 +set FIXTURE=tests\fixtures\sample.png +set TMP=%TEMP%\lab5-lease +if not exist "%TMP%" mkdir "%TMP%" + +call :guid +set RND=%GUIDVAL% +set U=lease%RND% +call :register "%U%" "Lease" u +if errorlevel 1 exit /b 1 +set UID=!u_ID! +call :login "%U%" u +if errorlevel 1 exit /b 1 +set TOKEN=!u_TOKEN! + +curl.exe -s -X POST "%BASE%/api/v1/chats" ^ + -H "Authorization: Bearer %TOKEN%" -H "Content-Type: application/json" ^ + -d "{\"title\":\"Lease expiry\",\"member_ids\":[\"%UID%\"]}" ^ + -o "%TMP%\chat.json" -w "%%{http_code}" > "%TMP%\chat.code" +call :check_code chat.code 201 "create chat" +if errorlevel 1 exit /b 1 +for /f "delims=" %%a in ('powershell -NoProfile -Command "(Get-Content '%TMP%\chat.json' -Raw | ConvertFrom-Json).id"') do set CHAT_ID=%%a + +echo === Stop worker and upload (job stays queued) === +docker compose --compatibility stop worker +curl.exe -s -X POST "%BASE%/api/v1/chats/%CHAT_ID%/attachments?filename=sample.png" ^ + -H "Authorization: Bearer %TOKEN%" -H "Content-Type: image/png" ^ + --data-binary "@%FIXTURE%" -o "%TMP%\att.json" -w "%%{http_code}" > "%TMP%\att.code" +call :check_code att.code 202 "upload" +if errorlevel 1 ( docker compose --compatibility up -d & exit /b 1 ) +for /f "delims=" %%a in ('powershell -NoProfile -Command "(Get-Content '%TMP%\att.json' -Raw | ConvertFrom-Json).id"') do set ATT_ID=%%a +echo attachment=%ATT_ID% + +echo === CASE A: expired lease on attempt 5 must become failed === +for /f "usebackq delims=" %%a in (`docker compose exec -T postgres psql -U messenger -d messenger -tAc "UPDATE jobs SET status='processing', attempt=5, lease_id='injected', lease_expires_at=now()-interval '2 minutes' WHERE attachment_id='%ATT_ID%'; UPDATE attachments SET status='processing' WHERE id='%ATT_ID%'; SELECT 'injected'"`) do set INJ=%%a +echo injection=%INJ% + +docker compose --compatibility start worker +powershell -NoProfile -Command "for($i=0;$i -lt 60;$i++){ $m=Invoke-RestMethod -Uri '%BASE%/api/v1/attachments/%ATT_ID%' -Headers @{Authorization='Bearer %TOKEN%'}; if($m.status -eq 'failed'){ $m | ConvertTo-Json -Depth 6 | Set-Content '%TMP%\a.json'; exit 0 }; Start-Sleep -Seconds 1 }; exit 1" +if errorlevel 1 ( + echo FAIL: expired lease on attempt 5 did not become failed + for /f "usebackq delims=" %%a in (`docker compose exec -T postgres psql -U messenger -d messenger -tAc "SELECT status || ':' || attempt FROM jobs WHERE attachment_id='%ATT_ID%'"`) do echo job state = %%a + exit /b 1 +) +for /f "delims=" %%a in ('powershell -NoProfile -Command "(Get-Content '%TMP%\a.json' -Raw | ConvertFrom-Json).error_code"') do set ECODE=%%a +echo PASS: case A failed with error_code=%ECODE% + +for /f "usebackq delims=" %%a in (`docker compose exec -T postgres psql -U messenger -d messenger -tAc "SELECT status || ':' || attempt FROM jobs WHERE attachment_id='%ATT_ID%'"`) do set JSTATE=%%a +echo job state after = %JSTATE% +if not "%JSTATE%"=="failed:5" ( echo FAIL: expected failed:5, got %JSTATE% & exit /b 1 ) +echo PASS: job row is failed:5 (no stuck processing:5) + +for /f "usebackq delims=" %%a in (`docker compose exec -T postgres psql -U messenger -d messenger -tAc "SELECT count(*) FROM job_failures WHERE attachment_id='%ATT_ID%'"`) do set FC=%%a +if "%FC%"=="0" ( echo FAIL: no job_failures row for case A & exit /b 1 ) +echo PASS: job_failures has %FC% row(s) + +echo === CASE B: expired lease on attempt 2 must be requeued and reach ready === +curl.exe -s -X POST "%BASE%/api/v1/chats/%CHAT_ID%/attachments?filename=sample2.png" ^ + -H "Authorization: Bearer %TOKEN%" -H "Content-Type: image/png" ^ + --data-binary "@%FIXTURE%" -o "%TMP%\att2.json" -w "%%{http_code}" > "%TMP%\att2.code" +call :check_code att2.code 202 "upload 2" +if errorlevel 1 exit /b 1 +for /f "delims=" %%a in ('powershell -NoProfile -Command "(Get-Content '%TMP%\att2.json' -Raw | ConvertFrom-Json).id"') do set ATT2=%%a + +for /f "usebackq delims=" %%a in (`docker compose exec -T postgres psql -U messenger -d messenger -tAc "UPDATE jobs SET status='processing', attempt=2, lease_id='injected', lease_expires_at=now()-interval '2 minutes' WHERE attachment_id='%ATT2%'; UPDATE attachments SET status='processing' WHERE id='%ATT2%'; SELECT 'injected'"`) do set INJ2=%%a +echo injection=%INJ2% + +powershell -NoProfile -Command "for($i=0;$i -lt 90;$i++){ $m=Invoke-RestMethod -Uri '%BASE%/api/v1/attachments/%ATT2%' -Headers @{Authorization='Bearer %TOKEN%'}; if($m.status -eq 'ready'){ exit 0 }; if($m.status -eq 'failed'){ exit 2 }; Start-Sleep -Seconds 1 }; exit 1" +if errorlevel 1 ( echo FAIL: case B did not reach ready & exit /b 1 ) +echo PASS: case B requeued after lease expiry and reached ready + +echo === No conn busy in worker logs === +docker compose logs worker --tail 300 > "%TMP%\worker.log" 2>&1 +findstr /i /c:"conn busy" "%TMP%\worker.log" >nul +if not errorlevel 1 ( echo FAIL: conn busy still present in worker logs & exit /b 1 ) +echo PASS: no conn busy in worker logs + +echo. +echo LEASE-EXPIRY CHECKS PASSED +exit /b 0 + +:guid +for /f "delims=" %%a in ('powershell -NoProfile -Command "[guid]::NewGuid().ToString('N').Substring(0,8)"') do set GUIDVAL=%%a +exit /b 0 + +:register +curl.exe -s -X POST "%BASE%/api/v1/users" ^ + -H "Content-Type: application/json" ^ + -d "{\"username\":\"%~1\",\"display_name\":\"%~2\",\"password\":\"%PASS%\"}" ^ + -o "%TMP%\%~3.json" -w "%%{http_code}" > "%TMP%\%~3.code" +set /p RC=<"%TMP%\%~3.code" +if not "%RC%"=="201" ( echo FAIL: register %~1, HTTP %RC% & type "%TMP%\%~3.json" & exit /b 1 ) +for /f "delims=" %%a in ('powershell -NoProfile -Command "(Get-Content '%TMP%\%~3.json' -Raw | ConvertFrom-Json).id"') do set "%~3_ID=%%a" +exit /b 0 + +:login +curl.exe -s -X POST "%BASE%/api/v1/auth/sessions" ^ + -u "%~1:%PASS%" ^ + -o "%TMP%\%~2.json" -w "%%{http_code}" > "%TMP%\%~2.code" +set /p RC=<"%TMP%\%~2.code" +if not "%RC%"=="201" ( echo FAIL: login %~1, HTTP %RC% & type "%TMP%\%~2.json" & exit /b 1 ) +for /f "delims=" %%a in ('powershell -NoProfile -Command "(Get-Content '%TMP%\%~2.json' -Raw | ConvertFrom-Json).token"') do set "%~2_TOKEN=%%a" +exit /b 0 + +:check_code +set /p RC=<"%TMP%\%~1" +if not "%RC%"=="%~2" ( echo FAIL: %~3 expected %~2, got %RC% & exit /b 1 ) +exit /b 0 \ No newline at end of file diff --git a/scripts/truncated-image.bat b/scripts/truncated-image.bat new file mode 100644 index 00000000..750b82ce --- /dev/null +++ b/scripts/truncated-image.bat @@ -0,0 +1,107 @@ +@echo off +setlocal EnableDelayedExpansion +cd /d "%~dp0.." + +set BASE=http://localhost:8080 +set PASS=Example-only-not-a-real-secret-123 +set FIXTURE=tests\fixtures\sample.png +set TMP=%TEMP%\lab5-truncated +if not exist "%TMP%" mkdir "%TMP%" + +call :guid +set RND=%GUIDVAL% +set U=trunc%RND% +call :register "%U%" "Truncated" u +if errorlevel 1 exit /b 1 +set UID=!u_ID! +call :login "%U%" u +if errorlevel 1 exit /b 1 +set TOKEN=!u_TOKEN! + +curl.exe -s -X POST "%BASE%/api/v1/chats" ^ + -H "Authorization: Bearer %TOKEN%" -H "Content-Type: application/json" ^ + -d "{\"title\":\"Truncated images\",\"member_ids\":[\"%UID%\"]}" ^ + -o "%TMP%\chat.json" -w "%%{http_code}" > "%TMP%\chat.code" +call :check_code chat.code 201 "create chat" +if errorlevel 1 exit /b 1 +for /f "delims=" %%a in ('powershell -NoProfile -Command "(Get-Content '%TMP%\chat.json' -Raw | ConvertFrom-Json).id"') do set CHAT_ID=%%a + +echo === Build truncated PNG (valid IHDR, cut IDAT, no IEND) === +powershell -NoProfile -Command "$b=[IO.File]::ReadAllBytes('%FIXTURE%'); $cut=[int]($b.Length*0.6); $out=New-Object byte[] $cut; [Array]::Copy($b,0,$out,0,$cut); [IO.File]::WriteAllBytes('%TMP%\truncated.png',$out); Write-Host ('truncated.png bytes='+$cut+' of '+$b.Length)" + +echo === Truncated PNG must be rejected with 415 at upload === +curl.exe -s -X POST "%BASE%/api/v1/chats/%CHAT_ID%/attachments?filename=truncated.png" ^ + -H "Authorization: Bearer %TOKEN%" -H "Content-Type: image/png" ^ + --data-binary "@%TMP%\truncated.png" ^ + -o "%TMP%\png.json" -w "%%{http_code}" > "%TMP%\png.code" +call :check_code png.code 415 "truncated png rejected at upload" +if errorlevel 1 ( type "%TMP%\png.json" & exit /b 1 ) +echo PASS: truncated PNG returned 415 (not 202) + +echo === Build valid JPEG, then truncate it === +powershell -NoProfile -Command "Add-Type -AssemblyName System.Drawing; $bmp=New-Object System.Drawing.Bitmap 64,64; for($x=0;$x -lt 64;$x++){ for($y=0;$y -lt 64;$y++){ $bmp.SetPixel($x,$y,[System.Drawing.Color]::FromArgb(($x*4),($y*4),128)) } }; $bmp.Save('%TMP%\full.jpg',[System.Drawing.Imaging.ImageFormat]::Jpeg); $bmp.Dispose(); $b=[IO.File]::ReadAllBytes('%TMP%\full.jpg'); $cut=[int]($b.Length*0.6); $out=New-Object byte[] $cut; [Array]::Copy($b,0,$out,0,$cut); [IO.File]::WriteAllBytes('%TMP%\truncated.jpg',$out); Write-Host ('truncated.jpg bytes='+$cut+' of '+$b.Length)" + +echo === Truncated JPEG must be rejected with 415 at upload === +curl.exe -s -X POST "%BASE%/api/v1/chats/%CHAT_ID%/attachments?filename=truncated.jpg" ^ + -H "Authorization: Bearer %TOKEN%" -H "Content-Type: image/jpeg" ^ + --data-binary "@%TMP%\truncated.jpg" ^ + -o "%TMP%\jpg.json" -w "%%{http_code}" > "%TMP%\jpg.code" +call :check_code jpg.code 415 "truncated jpeg rejected at upload" +if errorlevel 1 ( type "%TMP%\jpg.json" & exit /b 1 ) +echo PASS: truncated JPEG returned 415 (not 202) + +echo === Valid JPEG still accepted with 202 (no false positives) === +curl.exe -s -X POST "%BASE%/api/v1/chats/%CHAT_ID%/attachments?filename=full.jpg" ^ + -H "Authorization: Bearer %TOKEN%" -H "Content-Type: image/jpeg" ^ + --data-binary "@%TMP%\full.jpg" ^ + -o "%TMP%\ok.json" -w "%%{http_code}" > "%TMP%\ok.code" +call :check_code ok.code 202 "valid jpeg accepted" +if errorlevel 1 ( type "%TMP%\ok.json" & exit /b 1 ) +for /f "delims=" %%a in ('powershell -NoProfile -Command "(Get-Content '%TMP%\ok.json' -Raw | ConvertFrom-Json).id"') do set ATT_ID=%%a +powershell -NoProfile -Command "for($i=0;$i -lt 60;$i++){ $m=Invoke-RestMethod -Uri '%BASE%/api/v1/attachments/%ATT_ID%' -Headers @{Authorization='Bearer %TOKEN%'}; if($m.status -eq 'ready'){ exit 0 }; if($m.status -eq 'failed'){ exit 2 }; Start-Sleep -Seconds 1 }; exit 1" +if errorlevel 1 ( echo FAIL: valid jpeg did not reach ready & exit /b 1 ) +echo PASS: valid JPEG reached ready + +echo === Valid PNG still accepted (fixture regression) === +curl.exe -s -X POST "%BASE%/api/v1/chats/%CHAT_ID%/attachments?filename=sample.png" ^ + -H "Authorization: Bearer %TOKEN%" -H "Content-Type: image/png" ^ + --data-binary "@%FIXTURE%" ^ + -o "%TMP%\png_ok.json" -w "%%{http_code}" > "%TMP%\png_ok.code" +call :check_code png_ok.code 202 "valid png accepted" +if errorlevel 1 exit /b 1 +for /f "delims=" %%a in ('powershell -NoProfile -Command "(Get-Content '%TMP%\png_ok.json' -Raw | ConvertFrom-Json).id"') do set PATT=%%a +powershell -NoProfile -Command "for($i=0;$i -lt 60;$i++){ $m=Invoke-RestMethod -Uri '%BASE%/api/v1/attachments/%PATT%' -Headers @{Authorization='Bearer %TOKEN%'}; if($m.status -eq 'ready'){ exit 0 }; if($m.status -eq 'failed'){ exit 2 }; Start-Sleep -Seconds 1 }; exit 1" +if errorlevel 1 ( echo FAIL: valid png did not reach ready & exit /b 1 ) +echo PASS: valid PNG reached ready + +echo. +echo TRUNCATED-IMAGE CHECKS PASSED +exit /b 0 + +:guid +for /f "delims=" %%a in ('powershell -NoProfile -Command "[guid]::NewGuid().ToString('N').Substring(0,8)"') do set GUIDVAL=%%a +exit /b 0 + +:register +curl.exe -s -X POST "%BASE%/api/v1/users" ^ + -H "Content-Type: application/json" ^ + -d "{\"username\":\"%~1\",\"display_name\":\"%~2\",\"password\":\"%PASS%\"}" ^ + -o "%TMP%\%~3.json" -w "%%{http_code}" > "%TMP%\%~3.code" +set /p RC=<"%TMP%\%~3.code" +if not "%RC%"=="201" ( echo FAIL: register %~1, HTTP %RC% & type "%TMP%\%~3.json" & exit /b 1 ) +for /f "delims=" %%a in ('powershell -NoProfile -Command "(Get-Content '%TMP%\%~3.json' -Raw | ConvertFrom-Json).id"') do set "%~3_ID=%%a" +exit /b 0 + +:login +curl.exe -s -X POST "%BASE%/api/v1/auth/sessions" ^ + -u "%~1:%PASS%" ^ + -o "%TMP%\%~2.json" -w "%%{http_code}" > "%TMP%\%~2.code" +set /p RC=<"%TMP%\%~2.code" +if not "%RC%"=="201" ( echo FAIL: login %~1, HTTP %RC% & type "%TMP%\%~2.json" & exit /b 1 ) +for /f "delims=" %%a in ('powershell -NoProfile -Command "(Get-Content '%TMP%\%~2.json' -Raw | ConvertFrom-Json).token"') do set "%~2_TOKEN=%%a" +exit /b 0 + +:check_code +set /p RC=<"%TMP%\%~1" +if not "%RC%"=="%~2" ( echo FAIL: %~3 expected %~2, got %RC% & exit /b 1 ) +exit /b 0 \ No newline at end of file diff --git a/src/internal/api/handlers.go b/src/internal/api/handlers.go index a68e7d72..55861f5d 100644 --- a/src/internal/api/handlers.go +++ b/src/internal/api/handlers.go @@ -417,6 +417,13 @@ func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) { apperr.Write(w, id, apperr.PayloadTooLarge("image exceeds 40 megapixels")) return } + // LAB 5 (ревью): целостность файла проверяется ДО приёма задания. + // DecodeConfig читает только заголовок, поэтому усечённый PNG иначе + // ушёл бы в очередь и упал уже в worker. Ресурсные лимиты сохранены. + if ierr := validateImageIntegrity(data, contentType, width, height); ierr != nil { + apperr.Write(w, id, apperr.UnsupportedMedia("file is corrupted or truncated")) + return + } attID := uuid.NewString() stagingKey := store.StagingKey(chat.ID, attID) diff --git a/src/internal/api/image_integrity.go b/src/internal/api/image_integrity.go new file mode 100644 index 00000000..c0840aa3 --- /dev/null +++ b/src/internal/api/image_integrity.go @@ -0,0 +1,196 @@ +// Package api, image_integrity.go — проверка ЦЕЛОСТНОСТИ изображения до приёма +// задания (лаба 5, замечание ревью). +// +// Почему отдельный шаг: image.DecodeConfig читает только заголовок, поэтому +// усечённый PNG с валидным IHDR проходил приём и падал уже в worker. Контракт +// требует 415 на приёме для заведомо повреждённых файлов. +// +// Ресурсные ограничения сохранены: +// - размер тела ограничен http.MaxBytesReader (10 MiB) ДО чтения; +// - габариты и потолок 40 Мп проверены ДО вызова этой функции; +// - PNG проверяется структурно (CRC32 чанков + полный inflate IDAT в discard), +// без выделения пиксельного буфера; +// - JPEG декодируется полностью, но не более одной проверки одновременно +// на реплику (семафор), т.к. пиксельный буфер JPEG заметно меньше RGBA. +package api + +import ( + "bytes" + "compress/zlib" + "encoding/binary" + "errors" + "fmt" + "hash/crc32" + "image/jpeg" + "io" +) + +var pngSignature = []byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a} + +// jpegDecodeGate — не более одной полной JPEG-проверки на реплику. +var jpegDecodeGate = make(chan struct{}, 1) + +// validateImageIntegrity возвращает ошибку, если файл повреждён/усечён. +// Вызывается после sniffImage, сверки MIME и проверки потолка пикселей. +func validateImageIntegrity(data []byte, contentType string, width, height int) error { + switch contentType { + case "image/png": + return validatePNGIntegrity(data, width, height) + case "image/jpeg": + return validateJPEGIntegrity(data) + default: + return errors.New("unsupported image type") + } +} + +// validatePNGIntegrity — обход чанков с проверкой CRC, обязательный IEND и +// полная распаковка IDAT. Пиксели не материализуются. +func validatePNGIntegrity(data []byte, width, height int) error { + // 8 байт сигнатуры + 25 байт минимального IHDR-чанка. + if len(data) < len(pngSignature)+25 || !bytes.HasPrefix(data, pngSignature) { + return errors.New("png: missing signature or IHDR") + } + + pos := len(pngSignature) + var idat bytes.Buffer + var sawIEND bool + var bitDepth, colorType, interlace byte + + for pos+12 <= len(data) { + length := int(binary.BigEndian.Uint32(data[pos : pos+4])) + if length < 0 || pos+12+length > len(data) { + return errors.New("png: truncated chunk") + } + typ := data[pos+4 : pos+8] + payload := data[pos+8 : pos+8+length] + wantCRC := binary.BigEndian.Uint32(data[pos+8+length : pos+12+length]) + + h := crc32.NewIEEE() + _, _ = h.Write(typ) + _, _ = h.Write(payload) + if h.Sum32() != wantCRC { + return fmt.Errorf("png: bad CRC in %s chunk", typ) + } + + switch string(typ) { + case "IHDR": + if length != 13 { + return errors.New("png: bad IHDR length") + } + bitDepth = payload[8] + colorType = payload[9] + interlace = payload[12] + case "IDAT": + idat.Write(payload) + case "IEND": + sawIEND = true + } + + pos += 12 + length + if sawIEND { + break + } + } + + if !sawIEND { + return errors.New("png: missing IEND (truncated file)") + } + if idat.Len() == 0 { + return errors.New("png: no IDAT data") + } + + zr, err := zlib.NewReader(bytes.NewReader(idat.Bytes())) + if err != nil { + return fmt.Errorf("png: zlib header: %w", err) + } + defer zr.Close() + + expected, err := expectedRawPNGSize(width, height, int(bitDepth), int(colorType), int(interlace)) + if err != nil { + return err + } + + // limit+1 позволяет отличить «ровно ожидаемый объём» от «раздулось больше». + // Если поток ровно expected, zlib дочитывается до EOF и проверяет adler32. + n, err := io.Copy(io.Discard, io.LimitReader(zr, expected+1)) + if err != nil { + return fmt.Errorf("png: inflate IDAT: %w", err) + } + if n != expected { + return fmt.Errorf("png: inflated %d bytes, expected %d (truncated or malformed)", n, expected) + } + return nil +} + +// expectedRawPNGSize — точный объём распакованных scanline-данных PNG, +// включая фильтр-байт каждой строки и все проходы Adam7 при interlace=1. +func expectedRawPNGSize(width, height, bitDepth, colorType, interlace int) (int64, error) { + var channels int + switch colorType { + case 0: // grayscale + channels = 1 + case 2: // truecolor + channels = 3 + case 3: // palette + channels = 1 + case 4: // grayscale + alpha + channels = 2 + case 6: // truecolor + alpha + channels = 4 + default: + return 0, fmt.Errorf("png: unknown color type %d", colorType) + } + if width <= 0 || height <= 0 { + return 0, errors.New("png: non-positive dimensions") + } + + rowBytes := func(w int) int64 { + bits := int64(w) * int64(channels) * int64(bitDepth) + return 1 + (bits+7)/8 // 1 фильтр-байт + округление вверх до байта + } + + if interlace == 0 { + return int64(height) * rowBytes(width), nil + } + + // Adam7: семь проходов (xStart, yStart, xStep, yStep). + passes := [7][4]int{ + {0, 0, 8, 8}, {4, 0, 8, 8}, {0, 4, 4, 8}, {2, 0, 4, 4}, + {0, 2, 2, 4}, {1, 0, 2, 2}, {0, 1, 1, 2}, + } + var total int64 + for _, p := range passes { + pw, ph := 0, 0 + if width > p[0] { + pw = (width - p[0] + p[2] - 1) / p[2] + } + if height > p[1] { + ph = (height - p[1] + p[3] - 1) / p[3] + } + if pw > 0 && ph > 0 { + total += int64(ph) * rowBytes(pw) + } + } + if total == 0 { + return 0, errors.New("png: empty interlaced image") + } + return total, nil +} + +// validateJPEGIntegrity — маркеры SOI/EOI плюс полное декодирование под гейтом. +func validateJPEGIntegrity(data []byte) error { + if len(data) < 4 || data[0] != 0xFF || data[1] != 0xD8 { + return errors.New("jpeg: missing SOI marker") + } + if !bytes.HasSuffix(data, []byte{0xFF, 0xD9}) { + return errors.New("jpeg: missing EOI marker (truncated file)") + } + + jpegDecodeGate <- struct{}{} + defer func() { <-jpegDecodeGate }() + + if _, err := jpeg.Decode(bytes.NewReader(data)); err != nil { + return fmt.Errorf("jpeg: decode: %w", err) + } + return nil +} diff --git a/src/internal/store/jobs.go b/src/internal/store/jobs.go index f90e1e8b..632f89d9 100644 --- a/src/internal/store/jobs.go +++ b/src/internal/store/jobs.go @@ -142,7 +142,13 @@ func (s *Store) MarkOutboxPublished(ctx context.Context, id string) error { // ─────────────── Worker: claim / complete / fail / retry ─────────────── // ClaimJob — атомарный захват работы с lease. Возвращает nil, если job уже -// в терминальном состоянии или захвачена живой арендой (идемпотентность повтора). +// в терминальном состоянии, в backoff-окне, под живой арендой, либо попытки +// исчерпаны (такую работу закрывает только ReapExpiredLeases). +// +// ВАЖНО (ревью): attempt монотонен — GREATEST(jobs.attempt, $2). Старое +// сообщение-дубль с меньшим номером попытки НЕ может откатить счётчик назад +// и обойти ограниченный retry. Захват истёкшей аренды разрешён только пока +// attempt < max_attempts, иначе исчерпанную работу воскресил бы любой дубль. func (s *Store) ClaimJob(ctx context.Context, jobID string, attempt int, leaseID string, expiresAt time.Time) (*ClaimedJob, error) { tx, err := s.pool.Begin(ctx) if err != nil { @@ -153,17 +159,21 @@ func (s *Store) ClaimJob(ctx context.Context, jobID string, attempt int, leaseID var c ClaimedJob err = tx.QueryRow(ctx, ` UPDATE jobs - SET status = 'processing', attempt = $2, lease_id = $3, lease_expires_at = $4, updated_at = now() + SET status = 'processing', + attempt = GREATEST(jobs.attempt, $2), + lease_id = $3, + lease_expires_at = $4, + updated_at = now() WHERE id = $1 AND ( (status = 'queued' AND (next_attempt_at IS NULL OR next_attempt_at <= now())) - OR (status = 'processing' AND lease_expires_at < now()) + OR (status = 'processing' AND lease_expires_at < now() AND attempt < max_attempts) ) RETURNING id, attachment_id, attempt, pipeline_version`, jobID, attempt, leaseID, expiresAt.UTC()). Scan(&c.JobID, &c.AttachmentID, &c.Attempt, &c.PipelineVersion) if errors.Is(err, pgx.ErrNoRows) { - return nil, nil // не захватываемо: ready/failed/живая аренда + return nil, nil // не захватываемо: терминал / backoff / живая аренда / попытки исчерпаны } if err != nil { return nil, err @@ -309,9 +319,14 @@ func (s *Store) ScheduleRetry(ctx context.Context, attachmentID string, nextAt t return true, tx.Commit(ctx) } -// ReapExpiredLeases — защита от зависшего processing (уровень 4): истёкшая -// аренда возвращает job в queued (если остались попытки) или переводит в failed. -// Возвращает количество восстановленных работ. +// ReapExpiredLeases — защита от зависшего processing (уровень 4). +// Истёкшая аренда возвращает job в queued (если остались попытки) или +// переводит в failed с записью в реестр отказов. +// +// ВАЖНО (ревью): результат каждого RETURNING-запроса сначала полностью +// вычитывается в срез и закрывается, и только потом выполняются tx.Exec. +// Транзакция pgx держит одно соединение, поэтому запрос при открытом +// результате даёт "conn busy" и теряет фиксацию failed. func (s *Store) ReapExpiredLeases(ctx context.Context) (int, error) { tx, err := s.pool.Begin(ctx) if err != nil { @@ -319,6 +334,14 @@ func (s *Store) ReapExpiredLeases(ctx context.Context) (int, error) { } defer tx.Rollback(ctx) + type reapedJob struct { + jobID string + attachmentID string + attempt int + pipeline int + } + + // ── 1. Истёкшая аренда, попытки остались → обратно в queued ── rows, err := tx.Query(ctx, ` UPDATE jobs SET status = 'queued', lease_id = NULL, lease_expires_at = NULL, @@ -328,25 +351,21 @@ func (s *Store) ReapExpiredLeases(ctx context.Context) (int, error) { if err != nil { return 0, err } - type reaped struct { - jobID, attachmentID string - attempt, pipeline int - } - var list []reaped + var requeued []reapedJob for rows.Next() { - var r reaped + var r reapedJob if err := rows.Scan(&r.jobID, &r.attachmentID, &r.attempt, &r.pipeline); err != nil { rows.Close() return 0, err } - list = append(list, r) + requeued = append(requeued, r) } rows.Close() if err := rows.Err(); err != nil { return 0, err } - for _, r := range list { + for _, r := range requeued { if _, err := tx.Exec(ctx, ` UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1`, r.attachmentID); err != nil { @@ -373,8 +392,9 @@ func (s *Store) ReapExpiredLeases(ctx context.Context) (int, error) { } } - // Исчерпанные попытки на зависших арендах → failed. - exhausted, err := tx.Query(ctx, ` + // ── 2. Истёкшая аренда, попытки исчерпаны → failed ── + // Сначала вычитываем и закрываем результат, затем фиксируем отказ. + exhaustedRows, err := tx.Query(ctx, ` UPDATE jobs SET status = 'failed', lease_id = NULL, lease_expires_at = NULL, error_code = 'retry_exhausted', error_message = 'lease expired with no attempts left', @@ -384,44 +404,52 @@ func (s *Store) ReapExpiredLeases(ctx context.Context) (int, error) { if err != nil { return 0, err } - for exhausted.Next() { - var jobID, attachmentID string - var attempt int - if err := exhausted.Scan(&jobID, &attachmentID, &attempt); err != nil { - exhausted.Close() + var exhausted []reapedJob + for exhaustedRows.Next() { + var r reapedJob + if err := exhaustedRows.Scan(&r.jobID, &r.attachmentID, &r.attempt); err != nil { + exhaustedRows.Close() return 0, err } + exhausted = append(exhausted, r) + } + exhaustedRows.Close() + if err := exhaustedRows.Err(); err != nil { + return 0, err + } + + for _, r := range exhausted { if _, err := tx.Exec(ctx, ` UPDATE attachments SET status = 'failed', error_code = 'retry_exhausted', variants = '[]', updated_at = now() - WHERE id = $1`, attachmentID); err != nil { - exhausted.Close() + WHERE id = $1`, r.attachmentID); err != nil { return 0, err } if _, err := tx.Exec(ctx, ` INSERT INTO job_failures (id, job_id, attachment_id, error_code, error_message, attempt, failed_at) VALUES ($1,$2,$3,'retry_exhausted','lease expired with no attempts left',$4,now())`, - uuid.NewString(), jobID, attachmentID, attempt); err != nil { - exhausted.Close() + uuid.NewString(), r.jobID, r.attachmentID, r.attempt); err != nil { return 0, err } } - exhausted.Close() - if err := exhausted.Err(); err != nil { - return 0, err - } if err := tx.Commit(ctx); err != nil { return 0, err } - return len(list), nil + return len(requeued), nil } -// EnqueueDueRetries — планировщик отложенных повторов (laба 5, уровень 4). -// Задания, у которых истёк backoff (next_attempt_at <= now()), получают новое -// сообщение в outbox и сбрасывают срок. Тем самым задержка реально соблюдается, -// а не только хранится: поток Redis не умеет отложенную доставку, поэтому -// момент публикации контролирует этот планировщик. +// EnqueueDueRetries — планировщик отложенных повторов (лаба 5, уровень 4). +// +// Зачем нужен: Redis Streams не умеет отложенную доставку. Backoff хранится +// в jobs.next_attempt_at, а момент публикации контролирует этот планировщик: +// он выбирает задания, у которых срок настал, сбрасывает срок и пишет +// намерение опубликовать в outbox (той же транзакцией). +// +// ВАЖНО (замечание ревью): результат RETURNING-запроса сначала полностью +// вычитывается в срез и закрывается, и только потом выполняются tx.Exec. +// Транзакция pgx держит одно соединение, поэтому запрос при открытом +// результате даёт "conn busy". func (s *Store) EnqueueDueRetries(ctx context.Context) (int, error) { tx, err := s.pool.Begin(ctx) if err != nil { @@ -437,25 +465,28 @@ func (s *Store) EnqueueDueRetries(ctx context.Context) (int, error) { if err != nil { return 0, err } - type due struct { - jobID, attachmentID string - attempt, pipeline int + + type dueJob struct { + jobID string + attachmentID string + attempt int + pipeline int } - var list []due + var due []dueJob for rows.Next() { - var d due + var d dueJob if err := rows.Scan(&d.jobID, &d.attachmentID, &d.attempt, &d.pipeline); err != nil { rows.Close() return 0, err } - list = append(list, d) + due = append(due, d) } rows.Close() if err := rows.Err(); err != nil { return 0, err } - for _, d := range list { + for _, d := range due { msg := model.JobMessage{ SchemaVersion: 1, JobID: d.jobID, @@ -476,8 +507,9 @@ func (s *Store) EnqueueDueRetries(ctx context.Context) (int, error) { return 0, err } } + if err := tx.Commit(ctx); err != nil { return 0, err } - return len(list), nil + return len(due), nil } diff --git a/src/internal/store/queue.go b/src/internal/store/queue.go index 4474a732..9203ef52 100644 --- a/src/internal/store/queue.go +++ b/src/internal/store/queue.go @@ -91,8 +91,6 @@ func (q *Queue) Ack(ctx context.Context, msgID string) error { return q.rdb.XAck(ctx, QueueStreamKey, QueueGroup, msgID).Err() } -// ReclaimStale — забрать сообщения, которые держит упавший потребитель -// (minIdle больше lease TTL, чтобы не перехватывать живую долгую обработку). // ReclaimStale — забрать сообщения, которые держит упавший потребитель // (minIdle больше lease TTL, чтобы не перехватывать живую долгую обработку). // Второе возвращаемое значение XAutoClaim — курсор следующей страницы PEL;