Implement lab4 private S3 attachments and reconciliation track

This commit is contained in:
ferraronp
2026-11-12 18:15:42 +03:00
parent ec540a1a72
commit 87ce432b81
56 changed files with 2465 additions and 41 deletions
+84
View File
@@ -0,0 +1,84 @@
<#
.SYNOPSIS
Лабораторная 4, трек 5: стоимость полного reconcile на нескольких масштабах.
.DESCRIPTION
Не делает --apply и НЕ удаляет объекты. На каждом этапе делает 5 dry-run,
создаёт синтетические вложения через HTTP API и сохраняет CSV.
Запуск из корня lab4 при поднятом docker compose.
.EXAMPLE
powershell -ExecutionPolicy Bypass -File scripts/measure_reconcile.ps1
#>
param(
[ValidateRange(1,100)][int]$ConcurrentUploads = 10,
[ValidateRange(1,20)][int]$BatchesPerStage = 5,
[ValidateRange(2,30)][int]$ScanRepeats = 5,
[ValidateRange(2,6)][int]$Stages = 3
)
$ErrorActionPreference = 'Stop'
$env:PYTHONUTF8 = '1'
if (!(Test-Path '.env') -or !(Test-Path 'tests/attachments_concurrent.py')) {
throw 'Запустите скрипт из корня Lab4, где есть .env и tests/attachments_concurrent.py'
}
New-Item -ItemType Directory -Force evidence | Out-Null
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$rows = New-Object 'System.Collections.Generic.List[object]'
for ($stage = 0; $stage -lt $Stages; $stage++) {
Write-Host "`n=== Stage ${stage}: measuring $ScanRepeats dry-runs ===" -ForegroundColor Cyan
for ($repeat = 1; $repeat -le $ScanRepeats; $repeat++) {
# Docker Compose может печатать сообщения о контейнерах в stderr; JSON из CLI — stdout.
$raw = @(& docker compose --env-file .env run --rm -T reconcile python -m app.reconcile)
if ($LASTEXITCODE -ne 0) {
throw "Reconcile dry-run failed at stage=$stage repeat=$repeat"
}
$s = ($raw -join "`n").Trim()
try {
$parsed = $s | ConvertFrom-Json
} catch {
# На некоторых версиях Compose в stdout бывают служебные строки.
$a = $s.IndexOf('{'); $b = $s.LastIndexOf('}')
if ($a -lt 0 -or $b -le $a) { throw "No JSON in reconcile output: $s" }
$parsed = $s.Substring($a, $b-$a+1) | ConvertFrom-Json
}
if ($parsed.mode -ne 'dry-run' -or $parsed.errors.Count -ne 0 -or
$parsed.missing_both_unrecoverable.Count -ne 0) {
throw 'Unexpected reconciliation state: inspect output before continuing'
}
$item = [pscustomobject]@{
stage = $stage
repeat = $repeat
s3_keys_scanned = [int]$parsed.s3_keys_scanned
db_rows_scanned = [int]$parsed.db_rows_scanned
scan_elapsed_seconds = [double]$parsed.scan_elapsed_seconds
}
$rows.Add($item)
Write-Host ("scan {0}/{1}: S3={2}, DB={3}, t={4}s" -f $repeat,$ScanRepeats,$item.s3_keys_scanned,$item.db_rows_scanned,$item.scan_elapsed_seconds)
}
if ($stage -eq ($Stages - 1)) { break }
Write-Host "Creating $BatchesPerStage batches x $ConcurrentUploads synthetic attachments..." -ForegroundColor Yellow
for ($batch = 1; $batch -le $BatchesPerStage; $batch++) {
$outPath = "evidence/measure-upload-$stamp-stage$stage-batch$batch.json"
& python tests/attachments_concurrent.py --concurrency $ConcurrentUploads --output $outPath
if ($LASTEXITCODE -ne 0) { throw "Upload failed at stage=$stage batch=$batch" }
}
}
$csv = "evidence/reconcile-cost-$stamp.csv"
$rows | Export-Csv -Path $csv -Encoding UTF8 -NoTypeInformation -Delimiter ';'
Write-Host "`nSaved $csv" -ForegroundColor Green
$rows | Group-Object stage | ForEach-Object {
$items = @($_.Group)
$avg = ($items | Measure-Object scan_elapsed_seconds -Average).Average
$sorted = @($items | Sort-Object scan_elapsed_seconds)
$median = $sorted[[int][Math]::Floor($sorted.Count / 2)].scan_elapsed_seconds
[pscustomobject]@{
stage = $_.Name
keys = $items[0].s3_keys_scanned
rows = $items[0].db_rows_scanned
runs = $items.Count
mean_seconds = [Math]::Round($avg, 4)
median_seconds = [Math]::Round($median, 4)
}
} | Format-Table -AutoSize
Write-Host 'Measurements done. These are small-sample local observations, not scalability proof.'
+11
View File
@@ -0,0 +1,11 @@
@echo off
setlocal
cd /d "%~dp0.."
docker compose --env-file .env stop --timeout 5 lb api1 api2 s3 redis postgres
if errorlevel 1 exit /b 1
docker compose --env-file .env up -d --wait postgres redis s3 s3-bootstrap
if errorlevel 1 exit /b 1
docker compose --env-file .env up -d --no-deps api1 api2 lb
if errorlevel 1 exit /b 1
python scripts\wait_ready.py
exit /b %ERRORLEVEL%
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Preserve named volumes. Restart all state stores and both API processes.
docker compose --env-file .env stop --timeout 5 lb api1 api2 s3 redis postgres
docker compose --env-file .env up -d --wait postgres redis s3 s3-bootstrap
docker compose --env-file .env up -d --no-deps api1 api2 lb
python - <<'PY'
import time, urllib.request
for i in range(120):
try:
with urllib.request.urlopen('http://localhost:8080/health/ready', timeout=2) as response:
if response.status == 200:
print('[restart] all services ready')
break
except Exception:
pass
time.sleep(.5)
else:
raise SystemExit('[restart] health timeout')
PY
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Run tests/load.py in a second terminal while this script recreates API instances.
for replica in api1 api2; do
docker compose --env-file .env up -d --no-deps --force-recreate "$replica"
docker compose --env-file .env exec -T "$replica" python - <<'PY'
import time,urllib.request
for _ in range(40):
try:
if urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status==200:break
except Exception:pass
time.sleep(.5)
else:raise SystemExit('replica did not recover')
PY
sleep 3
done
+10
View File
@@ -0,0 +1,10 @@
@echo off
setlocal
cd /d "%~dp0.."
if "%TARGET_INSTANCE_ID%"=="api1" goto stop
if "%TARGET_INSTANCE_ID%"=="api2" goto stop
echo Unexpected TARGET_INSTANCE_ID 1>&2
exit /b 2
:stop
docker compose --env-file .env stop --timeout 1 %TARGET_INSTANCE_ID%
exit /b %ERRORLEVEL%
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
# The public failover test sets TARGET_INSTANCE_ID from the actual response header.
set -eu
cd "$(dirname "$0")/.."
case "${TARGET_INSTANCE_ID:?missing TARGET_INSTANCE_ID}" in
api1|api2) docker compose --env-file .env stop --timeout 1 "$TARGET_INSTANCE_ID" ;;
*) echo 'Unexpected instance alias' >&2; exit 2 ;;
esac
+14
View File
@@ -0,0 +1,14 @@
"""Operator-facing readiness wait after container replacement."""
import time
import urllib.request
for _ in range(120):
try:
with urllib.request.urlopen("http://localhost:8080/health/ready", timeout=2) as response:
if response.status == 200:
print("[restart] all services ready")
break
except Exception:
pass
time.sleep(.5)
else:
raise SystemExit("[restart] health timeout")