Основа из lab3
This commit is contained in:
@@ -8,8 +8,8 @@ import re
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def main():
|
||||
lab = json.loads((ROOT/'lab.json').read_text())['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
|
||||
lab = json.loads((ROOT/'lab.json').read_text(encoding='utf-8'))['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text(encoding='utf-8'))
|
||||
assert spec['openapi']=='3.1.0'
|
||||
assert spec['info']['version']=='1.%d.0'%lab
|
||||
operation_ids = set()
|
||||
@@ -41,11 +41,11 @@ def main():
|
||||
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
|
||||
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
|
||||
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
|
||||
ast.parse(file.read_text(),filename=str(file))
|
||||
ast.parse(file.read_text(encoding='utf-8'),filename=str(file))
|
||||
for file in ROOT.rglob('*.json'):
|
||||
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
|
||||
continue
|
||||
json.loads(file.read_text())
|
||||
json.loads(file.read_text(encoding='utf-8'))
|
||||
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
|
||||
assert (ROOT/required).is_file(), 'missing '+required
|
||||
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/bin/sh
|
||||
# Collect evidence for lab3 report. Redacts secrets before writing.
|
||||
# Usage: sh scripts/collect-evidence.sh
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
|
||||
redact() {
|
||||
# Strip Authorization headers, tokens, passwords from stdin.
|
||||
sed -E \
|
||||
-e 's/(Authorization:[[:space:]]*)[^[:space:]]+/\1<redacted>/Ig' \
|
||||
-e 's/("token"[[:space:]]*:[[:space:]]*")[^"]+/\1<redacted>/g' \
|
||||
-e 's/("password"[[:space:]]*:[[:space:]]*")[^"]+/\1<redacted>/g' \
|
||||
-e 's/(POSTGRES_PASSWORD=)[^[:space:]]+/\1<redacted>/g'
|
||||
}
|
||||
|
||||
run_step() {
|
||||
name="$1"; shift
|
||||
out="evidence/$name"
|
||||
echo "# $name — $(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$out"
|
||||
echo "# cmd: $*" >> "$out"
|
||||
if "$@" 2>&1 | redact >> "$out"; then
|
||||
echo "# status: OK" >> "$out"
|
||||
else
|
||||
echo "# status: FAILED" >> "$out"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_URL="${BASE_URL:-http://localhost:8080}"
|
||||
|
||||
run_step smoke.txt make test BASE_URL="$BASE_URL"
|
||||
run_step persistence.txt make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
run_step failover.txt make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
run_step dependency.txt python3 tests/test_dependency_failure.py --base-url "$BASE_URL"
|
||||
|
||||
# Instances: 6 requests, extract X-Instance-Id.
|
||||
{
|
||||
echo "# instances — $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo "# cmd: 6x curl -sI $BASE_URL/health/live"
|
||||
i=0
|
||||
while [ $i -lt 6 ]; do
|
||||
curl -sI "$BASE_URL/health/live" | grep -i '^x-instance-id:' || echo "x-instance-id: <missing>"
|
||||
i=$((i+1))
|
||||
done
|
||||
} > evidence/instances.txt
|
||||
|
||||
# Health with headers.
|
||||
{
|
||||
echo "# health — $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo "## /health/live"
|
||||
curl -s -D - -o /dev/null "$BASE_URL/health/live" | redact
|
||||
echo "## /health/ready"
|
||||
curl -s -D - -o /dev/null "$BASE_URL/health/ready" | redact
|
||||
} > evidence/health.txt
|
||||
|
||||
# Compose config (redacted).
|
||||
{
|
||||
echo "# compose-config — $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
docker compose --env-file .env config 2>&1 | redact
|
||||
} > evidence/compose-config.txt
|
||||
|
||||
# Migrate logs.
|
||||
{
|
||||
echo "# migrate — $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
docker compose --env-file .env logs migrate 2>&1 | redact
|
||||
} > evidence/migrate.txt
|
||||
|
||||
# Load test.
|
||||
{
|
||||
echo "# load — $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json 2>&1 | redact
|
||||
} > evidence/load.txt
|
||||
|
||||
echo "Evidence collected in evidence/"
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Ожидаем Index Scan по messages_chat_created_idx, без Seq Scan всей истории.
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000000'
|
||||
AND (created_at, id) > ('2026-01-01T00:00:00Z', '00000000-0000-4000-8000-000000000000')
|
||||
ORDER BY created_at, id
|
||||
LIMIT 51;
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Restart API replicas and PostgreSQL preserving volumes and data.
|
||||
# Does NOT remove volumes, does NOT re-seed, does NOT print credentials.
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --env-file .env restart postgres
|
||||
docker compose --env-file .env restart api-1 api-2
|
||||
# Wait for readiness through the LB.
|
||||
i=0
|
||||
while [ $i -lt 60 ]; do
|
||||
if curl -fsS http://localhost:8080/health/ready >/dev/null 2>&1; then
|
||||
exit 0
|
||||
fi
|
||||
i=$((i+1))
|
||||
sleep 1
|
||||
done
|
||||
echo "readiness timeout" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Создаёт >=10 000 сообщений и снимает EXPLAIN (ANALYZE, BUFFERS).
|
||||
|
||||
Запуск: python3 scripts/seed_history.py --count 10000 --output evidence/explain.txt
|
||||
Требует запущенный API (BASE_URL) и доступ к psql через docker compose exec.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def request(base, method, path, body=None, token=None, basic=None):
|
||||
headers = {"Accept": "application/json"}
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
if basic:
|
||||
headers["Authorization"] = "Basic " + basic
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(base + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
payload = resp.read()
|
||||
return resp.status, json.loads(payload) if payload else None
|
||||
except urllib.error.HTTPError as err:
|
||||
payload = err.read()
|
||||
return err.code, json.loads(payload) if payload else None
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="Seed history and run EXPLAIN")
|
||||
p.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
|
||||
p.add_argument("--count", type=int, default=10000)
|
||||
p.add_argument("--output", default="evidence/explain.txt")
|
||||
p.add_argument("--psql", default="docker compose exec -T postgres psql -U messenger -d messenger")
|
||||
args = p.parse_args()
|
||||
base = args.base_url.rstrip("/")
|
||||
|
||||
username = "u_seed_" + uuid.uuid4().hex[:10]
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
status, alice = request(base, "POST", "/api/v1/users",
|
||||
{"username": username, "display_name": "Seed", "password": password})
|
||||
assert status == 201, (status, alice)
|
||||
basic = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
status, session = request(base, "POST", "/api/v1/auth/sessions", basic=basic)
|
||||
assert status == 201, (status, session)
|
||||
token = session["token"]
|
||||
|
||||
status, chat = request(base, "POST", "/api/v1/chats",
|
||||
{"title": "Seed history", "member_ids": [alice["id"]]}, token=token)
|
||||
assert status == 201, (status, chat)
|
||||
chat_id = chat["id"]
|
||||
|
||||
started = time.monotonic()
|
||||
for i in range(args.count):
|
||||
status, _ = request(base, "POST", "/api/v1/chats/" + chat_id + "/messages",
|
||||
{"text": "seed-%d" % i}, token=token)
|
||||
if status != 201:
|
||||
raise SystemExit("failed to insert message %d: %s" % (i, status))
|
||||
if (i + 1) % 1000 == 0:
|
||||
print("inserted %d/%d" % (i + 1, args.count), file=sys.stderr)
|
||||
elapsed = time.monotonic() - started
|
||||
print("inserted %d messages in %.1fs" % (args.count, elapsed), file=sys.stderr)
|
||||
|
||||
sql = (
|
||||
"EXPLAIN (ANALYZE, BUFFERS) "
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages "
|
||||
"WHERE chat_id = '%s' "
|
||||
"AND (created_at, id) > ('1970-01-01T00:00:00Z', '00000000-0000-0000-0000-000000000000') "
|
||||
"ORDER BY created_at, id LIMIT 51;" % chat_id
|
||||
)
|
||||
proc = subprocess.run(args.psql.split() + ["-c", sql], cwd=str(ROOT),
|
||||
capture_output=True, text=True, timeout=120)
|
||||
if proc.returncode != 0:
|
||||
raise SystemExit("psql failed: " + proc.stderr[:500])
|
||||
out = proc.stdout
|
||||
dest = (ROOT / args.output).resolve()
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_text(
|
||||
"# chat_id=%s count=%d\n%s\n" % (chat_id, args.count, out),
|
||||
encoding="utf-8",
|
||||
)
|
||||
print(out)
|
||||
print("saved to " + str(dest), file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Поднимает PostgreSQL обратно и ждёт готовности.
|
||||
docker compose start postgres
|
||||
i=0
|
||||
while [ "$i" -lt 60 ]; do
|
||||
if docker compose exec -T postgres pg_isready -U messenger -d messenger >/dev/null 2>&1; then
|
||||
exit 0
|
||||
fi
|
||||
i=$((i+1))
|
||||
sleep 1
|
||||
done
|
||||
echo "postgres did not become ready" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Поднимает Redis обратно и ждёт готовности.
|
||||
docker compose start redis
|
||||
i=0
|
||||
while [ "$i" -lt 30 ]; do
|
||||
if docker compose exec -T redis redis-cli ping >/dev/null 2>&1; then
|
||||
exit 0
|
||||
fi
|
||||
i=$((i+1))
|
||||
sleep 1
|
||||
done
|
||||
echo "redis did not become ready" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Stop exactly one API replica identified by TARGET_INSTANCE_ID (api-1 or api-2).
|
||||
# Leaves it stopped; does not touch DB/LB/volumes.
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
cd "$(dirname "$0")/.."
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
api-1|api-2) ;;
|
||||
*) echo "unknown TARGET_INSTANCE_ID: $TARGET_INSTANCE_ID" >&2; exit 2 ;;
|
||||
esac
|
||||
docker compose --env-file .env stop "$TARGET_INSTANCE_ID"
|
||||
exit 0
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Останавливает PostgreSQL, сохраняя volume. Используется тестом недоступности.
|
||||
docker compose stop postgres
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Останавливает Redis, сохраняя volume. Используется тестом недоступности.
|
||||
docker compose stop redis
|
||||
@@ -6,17 +6,17 @@ from openapi_spec_validator import validate
|
||||
from jsonschema import Draft202012Validator
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
spec = json.loads((root/'contracts/openapi.json').read_text())
|
||||
spec = json.loads((root/'contracts/openapi.json').read_text(encoding='utf-8'))
|
||||
validate(spec)
|
||||
from referencing import Registry, Resource
|
||||
# The base URI resolves local #/components references inside examples.
|
||||
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
|
||||
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
|
||||
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
|
||||
for name, example in json.loads((root/'contracts/examples.json').read_text(encoding='utf-8')).items():
|
||||
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
|
||||
Draft202012Validator(schema, registry=registry).validate(example)
|
||||
for path in (root/'contracts').glob('*.schema.json'):
|
||||
schema = json.loads(path.read_text())
|
||||
schema = json.loads(path.read_text(encoding='utf-8'))
|
||||
Draft202012Validator.check_schema(schema)
|
||||
for example in schema.get('examples',[]):
|
||||
Draft202012Validator(schema).validate(example)
|
||||
|
||||
Reference in New Issue
Block a user