This commit is contained in:
2026-11-06 21:15:31 +03:00
parent 276dbdad8a
commit ef7e8c389e
219 changed files with 15212 additions and 57 deletions
+12
View File
@@ -0,0 +1,12 @@
$ErrorActionPreference = 'Stop'
New-Item -ItemType Directory -Force secrets | Out-Null
$values = @{postgres_db='messenger'; postgres_user='messenger'; postgres_password=''; minio_root_user='labadmin'; minio_root_password=''; s3_access_key_id='labapi'; s3_secret_access_key=''}
foreach ($name in $values.Keys) {
$path = Join-Path secrets ($name + '.txt')
if (!(Test-Path -LiteralPath $path)) {
$value = $values[$name]
if (!$value) { $value = [Convert]::ToBase64String([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) }
[System.IO.File]::WriteAllText((Join-Path (Get-Location) $path), $value)
}
}
if (!(Test-Path .env)) { Copy-Item .env.example .env }
+211
View File
@@ -0,0 +1,211 @@
import hashlib
import json
import math
import re
import subprocess
import sys
import xml.etree.ElementTree as ET
from datetime import datetime, timezone, timedelta
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from pipeline_support import compose, sql, broker, ready_api
def main():
ready_api()
stamp = datetime.now(timezone(timedelta(hours=3))).isoformat()
ids = compose("ps", "-q").splitlines()
inspection = json.loads(subprocess.check_output(["docker", "inspect", *ids], text=True))
allowed = {
"ROLE",
"JOB_MAX_ATTEMPTS",
"JOB_TIMEOUT_SECONDS",
"JOB_LEASE_SECONDS",
"MAX_PENDING_JOBS",
"FAULT_INJECTION_ENABLED",
}
containers = []
for item in inspection:
environment = {
v.split("=", 1)[0]: v.split("=", 1)[1]
for v in item["Config"]["Env"]
if v.split("=", 1)[0] in allowed
}
containers.append(
{
"name": item["Name"],
"image": item["Image"],
"started_at": item["State"]["StartedAt"],
"state": item["State"]["Status"],
"health": item["State"].get("Health", {}).get("Status"),
"volumes": [
{"name": m["Name"], "target": m["Destination"]}
for m in item["Mounts"]
if m["Type"] == "volume"
],
"memory_limit_bytes": item["HostConfig"]["Memory"],
"nano_cpus": item["HostConfig"]["NanoCpus"],
"profile": environment,
}
)
info = {
"time_moscow": stamp,
"base_commit": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(),
"source_lab4": "cc0ef71",
"worktree": "modified; source hashes below",
"docker": subprocess.check_output(
["docker", "info", "--format", "{{.ServerVersion}} CPU={{.NCPU}} RAM={{.MemTotal}}"],
text=True,
).strip(),
"containers": containers,
"job_states": sql(
"select status,count(*) from processing_jobs group by status order by status;"
),
"redis_durability": broker("CONFIG", "GET", "appendonly", "appendfsync"),
"broker_stream_entries": broker("XLEN", "attachment-jobs"),
"broker_publication_index_entries": broker("HLEN", "job-publications"),
}
(ROOT / "evidence/environment.json").write_text(json.dumps(info, ensure_ascii=False, indent=2))
capture_schema()
capture_metrics()
capture_final_checks()
files = list((ROOT / "src").rglob("*.java")) + list(
(ROOT / "src/main/resources").rglob("*.sql")
)
files += (
list((ROOT / "worker").rglob("*.py"))
+ list((ROOT / "tests").glob("*.py"))
+ list((ROOT / "scripts").glob("*"))
)
files += [
ROOT / p
for p in [
"build.gradle",
"settings.gradle",
".editorconfig",
"pyproject.toml",
"requirements-tools.txt",
"gradle/wrapper/gradle-wrapper.properties",
"Dockerfile",
"worker/Dockerfile",
"worker/requirements.txt",
"docker-compose.yml",
"compose.test.yaml",
"compose.local.yaml",
"nginx.conf",
"policy.json",
]
]
manifest = {
p.relative_to(ROOT).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest()
for p in files
if p.is_file()
}
(ROOT / "evidence/source-sha256.json").write_text(json.dumps(manifest, indent=2))
summary = [
{k: v for k, v in ET.parse(p).getroot().attrib.items() if k != "hostname"}
for p in (ROOT / "build/test-results/test").glob("TEST-*.xml")
]
(ROOT / "evidence/unit-summary.json").write_text(json.dumps(summary, indent=2))
targets = re.findall(r"\]\(([^)]+)\)", (ROOT / "REPORT.md").read_text())
missing = [t for t in targets if not t.startswith(("http", "#")) and not (ROOT / t).exists()]
if missing:
raise AssertionError("Missing report links: " + str(missing))
print("PASS environment, job schema, metrics, source hashes and report links")
def capture_schema():
from jsonschema import Draft202012Validator, FormatChecker
schema = json.loads((ROOT / "contracts/jobs.schema.json").read_text())
validator = Draft202012Validator(schema, format_checker=FormatChecker())
payloads = json.loads(
sql("select coalesce(json_agg(payload),'[]'::json) from processing_outbox;")
)
for payload in payloads:
validator.validate(payload)
(ROOT / "evidence/job-schema.json").write_text(
json.dumps({"validated_outbox_templates": len(payloads), "valid": True}, indent=2)
)
def capture_final_checks():
public = [
"README.md",
"lab.json",
"contracts",
"tests/client.py",
"tests/smoke.py",
"tests/resilience.py",
"tests/load.py",
"tests/image_probe.py",
]
subprocess.run(["git", "diff", "--exit-code", "--", *public], cwd=ROOT, check=True)
subprocess.run(["git", "diff", "--check"], cwd=ROOT, check=True)
names = (
subprocess.check_output(
["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], cwd=ROOT
)
.decode("utf-8")
.split("\0")
)
credentials = [
path.read_bytes().strip()
for path in (ROOT / "secrets").glob("*.txt")
if "password" in path.stem or "secret" in path.stem
]
for name in filter(None, names):
path = ROOT / name
if path.is_file() and any(value and value in path.read_bytes() for value in credentials):
raise AssertionError("Local credential value found in a Git-visible file")
subprocess.run(["git", "check-ignore", "--quiet", ".env"], cwd=ROOT, check=True)
for path in (ROOT / "secrets").glob("*.txt"):
subprocess.run(["git", "check-ignore", "--quiet", str(path)], cwd=ROOT, check=True)
(ROOT / "evidence/final-checks.txt").write_text(
"PASS public lab5 assignment, contract and executable tests unchanged\n"
"PASS no local credential values in Git-visible files; secrets and .env ignored\n"
"PASS git diff --check\n"
"Controller DI, single service call, API Javadoc and formatting: evidence/style.txt\n"
)
def capture_metrics():
raw = json.loads((ROOT / "evidence/backpressure.json").read_text())
peaks = {}
for sample in raw["stats_samples"]:
for name, value, unit, cpu in re.findall(
r"(\S+) ([\d.]+)(KiB|MiB|GiB) / \S+ ([\d.]+)%", sample
):
value = float(value) * {"KiB": 1 / 1024, "MiB": 1, "GiB": 1024}[unit]
current = peaks.setdefault(name, {"sampled_peak_MiB": 0, "sampled_peak_CPU_percent": 0})
current["sampled_peak_MiB"] = max(current["sampled_peak_MiB"], value)
current["sampled_peak_CPU_percent"] = max(
current["sampled_peak_CPU_percent"], float(cpu)
)
result = {
"profile": "6 accepted / 4 unavailable; 10 clients; 800x600 PNG",
"limits": "API 512MiB, worker 1GiB, dispatcher 256MiB",
"samples": len(raw["stats_samples"]),
"peaks": peaks,
"limitations": "discrete RSS/CPU samples, not true maximum or steady-state throughput",
}
(ROOT / "evidence/resource-summary.json").write_text(json.dumps(result, indent=2))
observations = sorted(raw["seconds_to_observed_ready"])
drain = {
"observed_ready_seconds": {
str(p): observations[max(0, math.ceil(p / 100 * len(observations)) - 1)]
for p in (50, 95, 99)
},
"accepted": raw["accepted"],
"expected_unavailable": raw["rejected"],
"image_bytes": raw["image_bytes"],
"polling_and_startup_included": True,
"interpretation": "upper bounds from sequential polls, n=6; not a steady-state latency SLA",
}
(ROOT / "evidence/drain-summary.json").write_text(json.dumps(drain, indent=2))
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
import hashlib
import json
from pathlib import Path
import sys
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from pipeline_support import compose, sql
def database_command(program, database, *arguments, data=None):
command = program + ' -U "$(cat /run/secrets/postgres_user)" "$@"'
return compose("exec", "-T", "db", "sh", "-c", command, "sh", *arguments, database, data=data)
def schema(database):
dump = database_command(
"pg_dump",
database,
"--schema-only",
"--no-owner",
"--no-privileges",
"--exclude-table=public.flyway_schema_history",
)
return "\n".join(
line
for line in dump.splitlines()
if not line.startswith(("\\restrict ", "\\unrestrict ", "-- Dumped "))
)
def main():
files = sorted((ROOT / "src/main/resources/db/migration").glob("*.sql"))
if [path.name for path in files] != ["V1__init.sql"]:
raise AssertionError("Expected exactly V1__init.sql")
database = "proof_v1_" + uuid.uuid4().hex
current = sql("select current_database();")
sql('create database "' + database + '";')
try:
database_command("psql", database, "-v", "ON_ERROR_STOP=1", data=files[0].read_text())
actual, expected = schema(database), schema(current)
if actual != expected:
raise AssertionError("Fresh V1 schema differs from existing migrated schema")
result = {
"migration": files[0].name,
"migration_sha256": hashlib.sha256(files[0].read_bytes()).hexdigest(),
"schema_sha256": hashlib.sha256(actual.encode()).hexdigest(),
"equivalent_to_existing_schema": True,
"excludes": "Flyway history and pg_dump random restriction tokens",
"temporary_database_removed": True,
}
finally:
sql('drop database "' + database + '" with (force);')
(ROOT / "evidence/migration-check.json").write_text(json.dumps(result, indent=2))
print(
"PASS one V1__init.sql; fresh PostgreSQL schema equals existing V1-V4 schema; temporary DB removed"
)
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
@powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.ps1"
+9
View File
@@ -0,0 +1,9 @@
$ErrorActionPreference = 'Stop'
$ids = docker compose ps -q
$before = docker inspect --format '{{.Name}} {{.State.StartedAt}}' $ids
$before | Set-Content evidence/restart-before.txt
docker compose restart db redis minio broker api worker dispatcher lb
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$ids = docker compose ps -q
$after = docker inspect --format '{{.Name}} {{.State.StartedAt}}' $ids
$after | Set-Content evidence/restart-after.txt
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
set -eu
docker compose restart db redis minio broker api worker dispatcher lb
+47
View File
@@ -0,0 +1,47 @@
$ErrorActionPreference = 'Stop'
Set-Location (Split-Path $PSScriptRoot -Parent)
$env:BASE_URL = 'http://127.0.0.1:18085'
$production = @('compose', '-f', 'docker-compose.yml', '-f', 'compose.local.yaml')
$testing = $production + @('-f', 'compose.test.yaml')
$summary = 'evidence/test-suite.txt'
"Started: $([DateTimeOffset]::Now.ToString('o'))" | Set-Content $summary
function Invoke-Check {
param([string]$Name, [string]$Executable, [string[]]$Arguments)
Write-Host "Running $Name"
& $Executable @Arguments *> "evidence/$Name.txt"
$result = $LASTEXITCODE
"$Name exit=$result at $([DateTimeOffset]::Now.ToString('o'))" | Add-Content $summary
if ($result -ne 0) {
Get-Content "evidence/$Name.txt" -Tail 30
throw "$Name failed ($result)"
}
}
try {
Invoke-Check 'style' 'py' @('scripts/style.py')
Invoke-Check 'contract-check' 'py' @('scripts/check_contract.py')
Invoke-Check 'openapi-validation' 'py' @('scripts/validate_openapi.py')
Invoke-Check 'java-build' '.\gradlew.bat' @('test', '--rerun-tasks')
Invoke-Check 'docker-build' 'docker' ($testing + @('up', '-d', '--build'))
& py -c "import sys;sys.path.insert(0,'tests');from pipeline_support import ready_api;ready_api()"
if ($LASTEXITCODE -ne 0) { throw 'API not ready' }
foreach ($name in @('smoke', 'pipeline_core', 'pipeline_faults', 'pipeline_retention', 'pipeline_boundaries', 'pipeline_ack_guard', 'pipeline_filename', 'pipeline_upload_crash', 'pipeline_history_capacity')) {
Invoke-Check ($name.Replace('_', '-')) 'py' @("tests/$name.py")
}
Invoke-Check 'production-restore' 'docker' ($production + @('up', '-d'))
& py -c "import sys;sys.path.insert(0,'tests');from pipeline_support import ready_api;ready_api()"
if ($LASTEXITCODE -ne 0) { throw 'production API not ready' }
Invoke-Check 'load' 'py' @('tests/load.py', '--duration', '30', '--concurrency', '4', '--output', 'evidence/load.json')
Invoke-Check 'persistence' 'py' @('tests/resilience.py', '--mode', 'persistence', '--action-script', 'scripts/restart.cmd')
& py -c "import sys;sys.path.insert(0,'tests');from pipeline_support import ready_api;ready_api()"
if ($LASTEXITCODE -ne 0) { throw 'Two routable API replicas required before failover' }
Invoke-Check 'failover' 'py' @('tests/resilience.py', '--mode', 'failover', '--action-script', 'scripts/stop-one.cmd')
Invoke-Check 'restore-api' 'docker' ($production + @('up', '-d', 'api'))
Invoke-Check 'smoke' 'py' @('tests/smoke.py')
Invoke-Check 'capture' 'py' @('scripts/capture_evidence.py')
'PASS all executable lab5 tests, validation and style checks' | Add-Content $summary
} finally {
& docker @production up -d
if ($LASTEXITCODE -ne 0) { throw 'Failed to restore production profile' }
}
+1
View File
@@ -0,0 +1 @@
@powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop-one.ps1"
+13
View File
@@ -0,0 +1,13 @@
$ErrorActionPreference = 'Stop'
$replicas = docker compose ps -q api
foreach ($replica in $replicas) {
$alias = docker inspect --format '{{.Config.Hostname}}' $replica
if ($alias -eq $env:TARGET_INSTANCE_ID) {
docker inspect --format "{{.Name}} {{.Config.Hostname}} {{.State.Status}}" $replica | Set-Content evidence/stop-one-before.txt
docker stop --time 2 $replica
$result = $LASTEXITCODE
docker inspect --format "{{.Name}} {{.Config.Hostname}} {{.State.Status}}" $replica | Set-Content evidence/stop-one-after.txt
exit $result
}
}
exit 1
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
for id in $(docker compose ps -q api); do
if [ "$(docker inspect --format '{{.Config.Hostname}}' "$id")" = "$TARGET_INSTANCE_ID" ]; then
docker stop -t 2 "$id"
exit 0
fi
done
exit 1
+88
View File
@@ -0,0 +1,88 @@
import argparse
import hashlib
import os
import re
from pathlib import Path
import subprocess
import sys
import tempfile
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
VERSION = "1.28.0"
SHA256 = "32342e7c1b4600f80df3471da46aee8012d3e1445d5ea1be1fb71289b07cc735"
def formatter():
jar = Path(tempfile.gettempdir()) / f"google-java-format-{VERSION}-all-deps.jar"
if not jar.exists():
url = (
"https://repo.maven.apache.org/maven2/com/google/googlejavaformat/"
f"google-java-format/{VERSION}/{jar.name}"
)
with urllib.request.urlopen(url, timeout=60) as response:
jar.write_bytes(response.read())
if hashlib.sha256(jar.read_bytes()).hexdigest() != SHA256:
raise RuntimeError("Java formatter checksum mismatch")
return jar
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--apply", action="store_true")
args = parser.parse_args()
java_home = os.environ.get("JAVA_HOME")
java = str(Path(java_home) / "bin" / "java") if java_home else "java"
files = sorted(str(p.relative_to(ROOT)) for p in (ROOT / "src").rglob("*.java"))
mode = ["--replace"] if args.apply else ["--dry-run", "--set-exit-if-changed"]
subprocess.run([java, "-jar", str(formatter()), "--aosp", *mode, *files], cwd=ROOT, check=True)
python = [
"worker/pipeline",
"scripts/style.py",
"scripts/capture_evidence.py",
"scripts/check_migration.py",
]
python += sorted(str(p.relative_to(ROOT)) for p in (ROOT / "tests").glob("pipeline_*.py"))
subprocess.run(
[sys.executable, "-m", "black", *([] if args.apply else ["--check"]), *python],
cwd=ROOT,
check=True,
)
check_controllers()
print("PASS Java AOSP / Python Black style")
def check_controllers():
directory = ROOT / "src/main/java/ru/mtusi/messenger/controller"
operations = 0
for path in directory.glob("*Controller.java"):
source = path.read_text(encoding="utf-8")
fields = re.findall(r"private final (\w+Service) (\w+);", source)
if "@RequiredArgsConstructor" not in source or len(fields) != 1:
raise AssertionError(f"Controller DI contract: {path.name}")
bodies = re.findall(r"@Override\s+public [^{}]+\{([^{}]*)\}", source)
if not bodies:
raise AssertionError(f"Controller has no operations: {path.name}")
service = fields[0][1]
for body in bodies:
if body.count(";") != 1 or len(re.findall(rf"\b{service}\.\w+\(", body)) != 1:
raise AssertionError(f"Controller must call one service: {path.name}")
if not re.fullmatch(rf"\s*(?:return )?{service}\.\w+\([^;]*\);\s*", body):
raise AssertionError(f"Controller contains extra logic: {path.name}")
operations += len(bodies)
for path in directory.glob("*Api.java"):
source = path.read_text(encoding="utf-8")
if source.count("/**") != source.count("@Operation(") + 1:
raise AssertionError(f"Missing API documentation: {path.name}")
for path in (ROOT / "src/main/java").rglob("*.java"):
source = path.read_text(encoding="utf-8")
if "@Autowired" in source:
raise AssertionError(f"Use constructor injection: {path.name}")
if re.search(r"^import .*\*;", source, re.MULTILINE):
raise AssertionError(f"Use explicit imports: {path.name}")
print(f"PASS {operations} controller operations: one service call, constructor DI, API Javadoc")
if __name__ == "__main__":
main()