#!/usr/bin/env python3 """Ответы самого LB соответствуют контракту: схема Error и X-Request-Id, равный request_id. Останавливает Valkey, чтобы LB вывел все реплики, и обязательно запускает его обратно. Запуск и сохранение результата: scripts/lb-errors-evidence.sh""" import http.client import json import pathlib import subprocess import sys import time ROOT = pathlib.Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) from client import shape # noqa: E402 def dc(*args): return subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT, capture_output=True, text=True) def get(path): conn = http.client.HTTPConnection('localhost', 8080, timeout=10) conn.request('GET', path) resp = conn.getresponse() return resp.status, {k.lower(): v for k, v in resp.getheaders()}, resp.read() def up_count(): csv = dc('exec', '-T', 'lb', 'wget', '-qO-', 'http://127.0.0.1:8404/stats;csv').stdout return sum(1 for line in csv.splitlines() if line.startswith('api,') and line.split(',')[1] != 'BACKEND' and line.split(',')[17].startswith('UP')) dc('stop', 'valkey') try: end = time.monotonic() + 15 while up_count() and time.monotonic() < end: time.sleep(0.2) status, headers, body = get('/api/v1/users/me') finally: dc('up', '-d', '--wait') error = json.loads(body) shape(error, 'Error') # падает, если тело не соответствует схеме print('статус: %d, Content-Type: %s, code: %s' % (status, headers.get('content-type'), error['error']['code'])) print('X-Request-Id есть: %s, равен request_id: %s, X-Instance-Id: %s (контракт разрешает отсутствие у ответов LB)' % ( bool(headers.get('x-request-id')), error['error']['request_id'] == headers.get('x-request-id'), headers.get('x-instance-id'))) ok = (status == 503 and 'application/json' in headers.get('content-type', '') and error['error']['code'] == 'unavailable' and error['error']['request_id'] == headers.get('x-request-id')) print('PASS' if ok else 'FAIL', 'ответ LB без рабочих реплик соответствует контракту') sys.exit(0 if ok else 1)