forked from mtusi2026/mtusi2026lab3
Проверять членство в чате раньше тела повторного ключа.
Исключённый участник получает 404 и на другой текст. Отдельная серия показывает, что при потолке CPU Postgres лишние реплики перестают поднимать RPS.
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
"""Removed member must get 404 on a repeated key before the body is compared.
|
||||
|
||||
Membership is revoked with DELETE in Postgres, the same way an isolated
|
||||
database check does it. The script prints status codes only.
|
||||
"""
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from client import Client
|
||||
import stand
|
||||
|
||||
UUID = re.compile(r'^[0-9a-fA-F-]{36}$')
|
||||
|
||||
|
||||
def revoke(user_id, chat_id):
|
||||
if UUID.fullmatch(user_id) is None or UUID.fullmatch(chat_id) is None:
|
||||
raise SystemExit('refusing to interpolate a non-uuid')
|
||||
sql = (
|
||||
"DELETE FROM chat_members WHERE user_id = '%s' AND chat_id = '%s'"
|
||||
% (user_id, chat_id)
|
||||
)
|
||||
stand.compose(['exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c', sql])
|
||||
|
||||
|
||||
def post(client, actor, chat_id, text, key, expected):
|
||||
result = client.call(
|
||||
'POST',
|
||||
'/api/v1/chats/%s/messages' % chat_id,
|
||||
expected,
|
||||
actor=actor,
|
||||
body={'text': text},
|
||||
headers={'Idempotency-Key': key},
|
||||
schema='Message' if expected == 201 else 'Error',
|
||||
)
|
||||
print('status', result['status'], 'expected', expected)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
stand.wait_ready()
|
||||
client = Client(stand.BASE, timeout=10)
|
||||
alice = client.user('acl')
|
||||
bob = client.user('aclpeer')
|
||||
chat = client.call(
|
||||
'POST',
|
||||
'/api/v1/chats',
|
||||
201,
|
||||
actor=alice,
|
||||
body={'title': 'Проверка ключа', 'member_ids': [alice['id'], bob['id']]},
|
||||
schema='Chat',
|
||||
)['json']
|
||||
key = 'same-' + uuid.uuid4().hex[:16]
|
||||
post(client, alice, chat['id'], 'первое', key, 201)
|
||||
post(client, alice, chat['id'], 'другое', key, 409)
|
||||
revoke(alice['id'], chat['id'])
|
||||
post(client, alice, chat['id'], 'другое', key, 404)
|
||||
post(client, alice, chat['id'], 'первое', key, 404)
|
||||
history = client.call(
|
||||
'GET',
|
||||
'/api/v1/chats/%s/messages' % chat['id'],
|
||||
404,
|
||||
actor=alice,
|
||||
schema='Error',
|
||||
)
|
||||
print('history', history['status'])
|
||||
print('access check passed')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Find the shared limit that stops extra API replicas from raising RPS.
|
||||
|
||||
Each API replica gets a whole core, so the earlier CPU-slicing effect is gone.
|
||||
Postgres is capped at 0.20 CPU for three points (1/2/4 replicas). A fourth
|
||||
point releases that cap to 1.0 CPU with the same four replicas. If RPS stops
|
||||
growing while Postgres sits on 0.20, and jumps when the cap is released, the
|
||||
database CPU is the saturation point.
|
||||
"""
|
||||
import json
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import stand
|
||||
|
||||
ROOT = stand.ROOT
|
||||
DURATION = 12
|
||||
CONCURRENCY = 16
|
||||
|
||||
RUNS = [
|
||||
{'name': 'pg020-r1', 'replicas': 1, 'pg_cpus': '0.20'},
|
||||
{'name': 'pg020-r2', 'replicas': 2, 'pg_cpus': '0.20'},
|
||||
{'name': 'pg020-r4', 'replicas': 4, 'pg_cpus': '0.20'},
|
||||
{'name': 'pg100-r4', 'replicas': 4, 'pg_cpus': '1.0'},
|
||||
]
|
||||
|
||||
|
||||
def deploy(cfg):
|
||||
env = {
|
||||
'API_CPUS': '1.0',
|
||||
'API_MEMORY': '256M',
|
||||
'CAP_MODE': 'off',
|
||||
'POOL_MAX': '4',
|
||||
'API_REPLICAS': str(cfg['replicas']),
|
||||
'POSTGRES_CPUS': cfg['pg_cpus'],
|
||||
'LB_CPUS': '0.50',
|
||||
'MAX_INFLIGHT_BODIES': '64',
|
||||
'MAX_PER_SECOND': '100000',
|
||||
}
|
||||
stand.compose(['up', '-d', '--no-deps', '--force-recreate', 'postgres'], extra_env=env)
|
||||
stand.compose(
|
||||
['up', '-d', '--no-deps', '--force-recreate', '--scale', 'api=%d' % cfg['replicas'], 'api'],
|
||||
extra_env=env,
|
||||
)
|
||||
stand.compose(['up', '-d', '--no-deps', '--force-recreate', 'lb'], extra_env=env)
|
||||
stand.wait_ready(timeout=120)
|
||||
|
||||
|
||||
def run_load(output):
|
||||
samples = []
|
||||
stop = {'flag': False}
|
||||
|
||||
def stats():
|
||||
while not stop['flag']:
|
||||
try:
|
||||
samples.append(stand.sample_stats())
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
|
||||
thread = threading.Thread(target=stats)
|
||||
thread.start()
|
||||
completed = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
str(ROOT / 'tests' / 'load.py'),
|
||||
'--base-url', stand.BASE,
|
||||
'--duration', str(DURATION),
|
||||
'--concurrency', str(CONCURRENCY),
|
||||
'--output', str(output),
|
||||
],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
stop['flag'] = True
|
||||
thread.join()
|
||||
report = json.loads(output.read_text(encoding='utf-8')) if output.exists() else {}
|
||||
report['load_exit'] = completed.returncode
|
||||
if completed.returncode != 0 and 'successful_requests' not in report:
|
||||
report['stderr_tail'] = (completed.stderr or completed.stdout or '')[-400:]
|
||||
return report, samples
|
||||
|
||||
|
||||
def restore():
|
||||
stand.compose(
|
||||
['up', '-d', '--no-deps', '--force-recreate', 'postgres'],
|
||||
extra_env={'POSTGRES_CPUS': '1.0'},
|
||||
)
|
||||
stand.compose(
|
||||
['up', '-d', '--no-deps', '--force-recreate', '--scale', 'api=2', 'api'],
|
||||
extra_env={
|
||||
'API_CPUS': '0.50',
|
||||
'API_MEMORY': '512M',
|
||||
'CAP_MODE': 'off',
|
||||
'POOL_MAX': '4',
|
||||
'API_REPLICAS': '2',
|
||||
'MAX_INFLIGHT_BODIES': '32',
|
||||
'MAX_PER_SECOND': '10000',
|
||||
},
|
||||
)
|
||||
stand.compose(
|
||||
['up', '-d', '--no-deps', '--force-recreate', 'lb'],
|
||||
extra_env={'LB_CPUS': '0.50'},
|
||||
)
|
||||
stand.wait_ready(timeout=120)
|
||||
|
||||
|
||||
def main():
|
||||
info = subprocess.run(['docker', 'info', '--format', '{{.NCPU}} {{.MemTotal}}'], text=True, capture_output=True)
|
||||
rows = []
|
||||
for cfg in RUNS:
|
||||
print('run %s' % cfg['name'], flush=True)
|
||||
deploy(cfg)
|
||||
output = ROOT / 'evidence' / ('load-sat-%s.json' % cfg['name'])
|
||||
report, samples = run_load(output)
|
||||
rows.append({
|
||||
'name': cfg['name'],
|
||||
'replicas': cfg['replicas'],
|
||||
'api_cpus_each': '1.0',
|
||||
'postgres_cpus': cfg['pg_cpus'],
|
||||
'lb_cpus': '0.50',
|
||||
'pool_max': 4,
|
||||
'concurrency': CONCURRENCY,
|
||||
'duration_seconds': DURATION,
|
||||
'successful_rps': report.get('successful_rps'),
|
||||
'failed_requests': report.get('failed_requests'),
|
||||
'successful_requests': report.get('successful_requests'),
|
||||
'latency_ms': report.get('successful_latency_ms'),
|
||||
'cpu_api_mean': stand.mean_cpu(samples, '-api-'),
|
||||
'cpu_postgres_mean': stand.mean_cpu(samples, '-postgres-'),
|
||||
'cpu_lb_mean': stand.mean_cpu(samples, '-lb-'),
|
||||
'load_exit': report.get('load_exit'),
|
||||
})
|
||||
print(json.dumps(rows[-1], ensure_ascii=False), flush=True)
|
||||
evidence = {
|
||||
'question': 'With a whole core per API replica, extra replicas stop helping when Postgres CPU is the shared cap.',
|
||||
'method': 'tests/load.py closed-loop POST, 12s, concurrency 16, one run each. Postgres limit 0.20 CPU for 1/2/4 replicas, then the same 4 replicas with Postgres limit 1.0.',
|
||||
'host': {
|
||||
'platform': platform.platform(),
|
||||
'python': platform.python_version(),
|
||||
'docker_info': (info.stdout or '').strip(),
|
||||
},
|
||||
'note': 'docker stats 100 percent is one core. A 0.20 CPU limit is saturated near 20 percent.',
|
||||
'runs': rows,
|
||||
}
|
||||
dest = ROOT / 'evidence' / 'saturation.json'
|
||||
dest.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
|
||||
restore()
|
||||
print('restored', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user