#!/bin/sh set -eu # Совместимость текущей схемы с предыдущей версией API — условие rolling update: # миграции применяются до замены реплик, и старые реплики продолжают работать. # Образ собирается из коммита PREVIOUS_REVISION (по умолчанию lab2-код aa971fb), # запускается одним процессом в сети backend рабочего стенда (наружу порт # не публикуется) и выполняет вход, создание чата, запись и чтение сообщения. # Создаются только синтетические данные; volumes не затрагиваются. cd "$(dirname "$0")/.." ENV_FILE="${ENV_FILE:-.env}" REVISION="${PREVIOUS_REVISION:-aa971fb}" IMAGE="mtusi-messenger:compat-$REVISION" NETWORK=messenger-lab3_backend git archive "$REVISION" | docker build --quiet --tag "$IMAGE" - >/dev/null echo "previous version image: $IMAGE ($(git log -1 --format='%h %s' "$REVISION"))" echo "schema on stand: $(docker compose --env-file "$ENV_FILE" exec -T postgres sh -c \ 'psql -X -q -tA -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT string_agg(name, \$\$, \$\$ ORDER BY version) FROM schema_migrations;"')" docker run --rm -i --network "$NETWORK" --env-file "$ENV_FILE" \ -e DB_HOST=postgres -e DB_PORT=5432 -e VALKEY_HOST=valkey -e VALKEY_PORT=6379 \ "$IMAGE" sh -c 'python src/gateway.py >/tmp/api.log 2>&1 & exec python -' <<'EOF' import base64 import json import time import urllib.error import urllib.request import uuid BASE = "http://127.0.0.1:8080" def call(method, path, body=None, headers=None): data = None if body is None else json.dumps(body).encode() request = urllib.request.Request(BASE + path, data=data, method=method) request.add_header("Content-Type", "application/json") for name, value in (headers or {}).items(): request.add_header(name, value) try: with urllib.request.urlopen(request, timeout=5) as response: return response.status, json.loads(response.read() or b"null") except urllib.error.HTTPError as error: return error.code, None for _ in range(60): try: if call("GET", "/health/ready")[0] == 200: break except OSError: pass time.sleep(0.5) else: print(open("/tmp/api.log").read()[-2000:]) raise SystemExit("FAIL: previous version did not become ready on current schema") username = "compat_" + uuid.uuid4().hex[:12] password = "Compat-" + uuid.uuid4().hex status_user, user = call( "POST", "/api/v1/users", {"username": username, "display_name": "Compat", "password": password}, ) credentials = base64.b64encode(f"{username}:{password}".encode()).decode() status_login, session = call( "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + credentials} ) bearer = {"Authorization": "Bearer " + session["token"]} status_chat, chat = call( "POST", "/api/v1/chats", {"title": "compat", "member_ids": [user["id"]]}, bearer ) path = f"/api/v1/chats/{chat['id']}/messages" status_send, message = call("POST", path, {"text": "старая версия пишет"}, bearer) status_read, page = call("GET", path, headers=bearer) result = { "ready": True, "register": status_user, "login": status_login, "create_chat": status_chat, "send_message_without_key": status_send, "read_history": status_read, "history_matches": page["items"] == [message], } print(json.dumps(result, ensure_ascii=False)) log = open("/tmp/api.log").read() print("startup log:", [line.split(" - ", 1)[-1] for line in log.splitlines() if "миграц" in line.lower() or "Схема" in line]) if any(code >= 400 for code in result.values() if isinstance(code, int)) or not result["history_matches"]: raise SystemExit("FAIL: previous version is not compatible with current schema") print("PASS: previous API version works on the current schema (expand-only migration)") EOF