lab3: Nginx, реплики и идемпотентность

This commit is contained in:
2026-11-06 20:20:43 +03:00
parent 0ab3a341aa
commit 69102247bc
69 changed files with 5271 additions and 38 deletions
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""Concurrency evidence for level 4: N clients write M messages in parallel.
Command (see REPORT.md and `make concurrency`):
python3 student-tests/concurrency.py --clients 10 --messages-per-client 10 \
--output evidence/concurrency.json
Expectation: every acknowledged message is stored exactly once, the full history
contains exactly clients*messages_per_client unique messages and the order over
pages is strictly increasing by (created_at, id). No retries are hidden: any
failed write is reported and fails the run.
"""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import sys
import threading
import time
import uuid
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, LAB, arguments, check, timestamp # noqa: E402
MESSAGES_PATH = '/api/v1/chats/%s/messages'
def build_fixture(base_url, ca_file, clients):
"""One user per client plus a single chat everybody belongs to."""
master = Client(base_url, ca_file, timeout=15)
master.call('GET', '/health/ready', schema='Health')
actors = [master.user('conc%d' % index) for index in range(clients)]
chat = master.call('POST', '/api/v1/chats', 201, actor=actors[0],
body={'title': 'Конкурентная запись',
'member_ids': [actor['id'] for actor in actors]},
schema='Chat')['json']
check(set(chat['member_ids']) == {actor['id'] for actor in actors},
'chat membership mismatch')
return master, actors, chat
def write_phase(base_url, ca_file, actors, chat, messages_per_client, prefix):
"""Each client writes its own slice of messages, all starting at once."""
barrier = threading.Barrier(len(actors))
def worker(index):
client = Client(base_url, ca_file, timeout=15)
actor = actors[index]
barrier.wait()
acknowledged, errors = [], []
started = time.monotonic()
for message_index in range(messages_per_client):
text = '%s-%03d-%03d' % (prefix, index, message_index)
try:
message = client.message(actor, chat, text)['json']
acknowledged.append((text, message['id']))
except Failure as exc:
errors.append('%s: %s' % (text, exc))
return {'client_index': index, 'acknowledged': acknowledged, 'errors': errors,
'duration_seconds': round(time.monotonic() - started, 3)}
started = time.monotonic()
with ThreadPoolExecutor(max_workers=len(actors)) as pool:
results = list(pool.map(worker, range(len(actors))))
return results, round(time.monotonic() - started, 3)
def read_whole_history(client, actor, chat):
items, cursor, pages = [], None, 0
while True:
query = '?limit=100' + ('' if cursor is None else '&cursor=' + quote(cursor, safe=''))
page = client.call('GET', MESSAGES_PATH % chat['id'] + query, actor=actor,
schema='MessagePage')['json']
items.extend(page['items'])
pages += 1
cursor = page['next_cursor']
check(pages < 100, 'pagination did not terminate')
if cursor is None:
return items, pages
def main():
def configure(parser):
parser.add_argument('--clients', type=int, default=10)
parser.add_argument('--messages-per-client', type=int, default=10)
parser.add_argument('--output', default=None,
help='Optional JSON report path, no session data inside')
args = arguments('Concurrent writes from independent HTTP clients', configure)
check(1 <= args.clients <= 64, 'clients must be 1..64')
check(1 <= args.messages_per_client <= 200, 'messages-per-client must be 1..200')
expected = args.clients * args.messages_per_client
prefix = 'conc-' + uuid.uuid4().hex[:8]
master, actors, chat = build_fixture(args.base_url, args.ca_file, args.clients)
results, elapsed = write_phase(args.base_url, args.ca_file, actors, chat,
args.messages_per_client, prefix)
acknowledged = [pair for result in results for pair in result['acknowledged']]
errors = [error for result in results for error in result['errors']]
history, pages = read_whole_history(master, actors[0], chat)
stored_texts = [message['text'] for message in history]
stored_ids = [message['id'] for message in history]
expected_texts = {'%s-%03d-%03d' % (prefix, client, index)
for client in range(args.clients)
for index in range(args.messages_per_client)}
missing = sorted(expected_texts.difference(stored_texts))
keys = [(timestamp(message['created_at']), uuid.UUID(message['id']).int)
for message in history]
ordered_correctly = all(keys[index] < keys[index + 1] for index in range(len(keys) - 1))
report = {
'lab': LAB,
'workload': 'closed-loop parallel POST messages from independent clients',
'clients': args.clients,
'messages_per_client': args.messages_per_client,
'expected_messages': expected,
'acknowledged_201': len(acknowledged),
'stored_in_history': len(history),
'unique_stored_ids': len(set(stored_ids)),
'unique_stored_texts': len(set(stored_texts)),
'duplicates': len(stored_ids) - len(set(stored_ids)),
'missing_texts': missing,
'failed_writes': len(errors),
'write_errors': errors[:10],
'history_pages': pages,
'history_order_strictly_increasing': ordered_correctly,
'writers_elapsed_seconds': elapsed,
'successful_rps': round(len(acknowledged) / elapsed, 3) if elapsed else None,
'per_client': [{'client_index': result['client_index'],
'acknowledged': len(result['acknowledged']),
'errors': len(result['errors']),
'duration_seconds': result['duration_seconds']}
for result in sorted(results, key=lambda item: item['client_index'])],
'note': ('Client-observed timings: closed-loop, single Docker host, no retries. '
'Latency percentiles are intentionally absent here (see make load).'),
}
text = json.dumps(report, ensure_ascii=False, indent=2)
if args.output:
destination = Path(args.output)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(text + '\n')
print(text)
check(not errors, 'some parallel writes failed')
check(len(acknowledged) == expected, 'not every write was acknowledged')
check(len(history) == expected, 'history holds %d messages instead of %d'
% (len(history), expected))
check(not missing, 'messages missing from the history')
check(len(set(stored_ids)) == expected, 'duplicate message ids in the history')
check(ordered_correctly, 'history is not strictly ordered by (created_at, id)')
print('PASS: %d parallel messages from %d clients stored exactly once' %
(expected, args.clients))
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', exc)
raise SystemExit(1)
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""Previous-lab regressions: durable replay, expiry, rollback and dependency failures."""
from concurrent.futures import ThreadPoolExecutor
import base64
import json
from pathlib import Path
import subprocess
import sys
import time
import uuid
import urllib.request
import urllib.error
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, arguments, check, run
import manage
def main():
def configure(p):
p.add_argument('--mode', choices=('storage', 'expiry'), default='storage')
args = arguments(__doc__, configure)
c = Client(args.base_url, args.ca_file, timeout=10)
if args.mode == 'expiry':
alice = c.user('expiry')
c.call('GET', '/api/v1/users/me', actor=alice)
time.sleep(3)
for _ in range(8):
c.call('GET', '/api/v1/users/me', 401, actor=alice)
print('PASS: short SESSION_TTL_SECONDS expiry across replicas')
return
alice, bob, eve, chat = c.bootstrap()
# Unique constraint must settle simultaneous registration.
body = dict(alice['registration'], username='race_' + uuid.uuid4().hex[:20])
def register(_):
return Client(args.base_url,args.ca_file).call('POST','/api/v1/users',[201,409],body=body)['status']
with ThreadPoolExecutor(max_workers=2) as pool:
check(sorted(pool.map(register,range(2)))==[201,409], 'registration race corrupted uniqueness')
before = c.call('GET','/api/v1/chats?limit=100',actor=alice,schema='ChatPage')['json']
c.call('POST','/api/v1/chats',400,actor=alice,
body={'title':'Rollback','member_ids':[alice['id'],str(uuid.uuid4())]})
after = c.call('GET','/api/v1/chats?limit=100',actor=alice,schema='ChatPage')['json']
check(before==after, 'invalid chat left a visible partial object')
key = uuid.uuid4().hex
original = c.message(alice,chat,'Replay after full restart',key=key)['json']
try:
manage.compose('stop','redis')
check(c.message(alice,chat,'Redis down')['status']==201, 'Redis failure broke writes')
c.call('GET','/api/v1/users/me',401)
manage.start_services('redis')
manage.wait_healthy('redis')
# Revoking with Redis unavailable must still invalidate the authoritative DB.
temp = c.user('revoke')
manage.compose('stop','redis')
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=temp)
manage.start_services('redis')
manage.wait_healthy('redis')
for _ in range(4):
c.call('GET','/api/v1/users/me',401,actor=temp)
manage.compose('stop','postgres')
# LB may answer 502 when every unready backend is excluded. Verify
# API's own dependency semantics inside its private network separately.
source = """import json,sys,urllib.request,urllib.error
actor=json.load(sys.stdin)
for path,want in [('/health/live',200),('/health/ready',503),('/api/v1/users/me',503)]:
req=urllib.request.Request('http://127.0.0.1:8080'+path,headers={'Authorization':'Bearer '+actor['token']})
try:
response=urllib.request.urlopen(req,timeout=8)
except urllib.error.HTTPError as exc:
response=exc
assert response.code==want,(path,response.code,want)
response.close()
print('PASS: API liveness 200, readiness/business 503 while PostgreSQL is down')
"""
subprocess.run(['docker','compose','exec','-T','api-a','python','-c',source],
cwd=ROOT,input=json.dumps({'token':alice['token']}),text=True,check=True)
try:
response=urllib.request.urlopen(c.base+'/api/v1/users/me',timeout=8)
except urllib.error.HTTPError as exc:
response=exc
check(response.code in (401,502,503,504), 'LB must reject unavailable/unauthenticated request')
response.close()
finally:
manage.start_services('postgres','redis')
for s in ('postgres','redis',*manage.SERVICES):
manage.wait_healthy(s)
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
# Stronger persistence check than public smoke: replay an OLD key as well.
manage.restart()
check(c.message(alice,chat,original['text'],key=key)['json']==original, 'idempotency lost on restart')
print('PASS: registration race, invalid chat rollback, Redis fallback, logout, DB 503, restart replay with original token/key')
if __name__ == '__main__':
run(main)
+207
View File
@@ -0,0 +1,207 @@
#!/usr/bin/env python3
"""Repeatable read/write load with explicit stop/update and sanitized evidence."""
from concurrent.futures import ThreadPoolExecutor
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
import uuid
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check, run
import manage
def whole_history(client, actor, chat):
items, cursor = [], None
while True:
path = '/api/v1/chats/%s/messages?limit=100' % chat['id']
if cursor:
path += '&cursor=' + quote(cursor, safe='')
page = client.call('GET', path, actor=actor, schema='MessagePage')['json']
items.extend(page['items'])
cursor = page['next_cursor']
if cursor is None:
return items
def scenario(args, service=None):
c = Client(args.base_url, args.ca_file, timeout=2)
alice, bob, eve, chat = c.bootstrap()
seed_key = uuid.uuid4().hex
seed = c.message(alice, chat, 'До воздействия', key=seed_key)['json']
events, samples, confirmations = [], [], {}
lock = threading.Lock()
started = time.monotonic()
end = threading.Event()
workload_started = threading.Barrier(5)
def load(worker_id):
local = Client(args.base_url, args.ca_file, timeout=2)
key = uuid.uuid4().hex
workload_started.wait()
while not end.is_set():
text = 'experiment-%d-%s' % (worker_id, key)
start = time.monotonic()
try:
reply = local.message(alice, chat, text, key=key)
with lock:
confirmations[text] = reply['json']
event = {'kind': 'write', 'ok': True, 'instance': reply['headers']['X-Instance-Id']}
key = uuid.uuid4().hex
except Failure:
event = {'kind': 'write', 'ok': False}
# Keep the same body/key after uncertain response.
event.update(at=time.monotonic() - started, elapsed=time.monotonic() - start)
with lock:
events.append(event)
start = time.monotonic()
try:
local.call('GET', '/api/v1/chats/%s/messages?limit=1' % chat['id'], actor=bob, schema='MessagePage')
ok = True
except Failure:
ok = False
with lock:
events.append({'kind': 'read', 'ok': ok, 'at': time.monotonic()-started,
'elapsed': time.monotonic()-start})
def stats():
ids = [x for name in (*manage.SERVICES, 'nginx', 'postgres', 'redis') for x in manage.containers(name)]
while not end.is_set():
proc = subprocess.run(['docker', 'stats', '--no-stream', '--format', '{{json .}}', *ids],
text=True, capture_output=True, timeout=10)
with lock:
samples.append({'at': round(time.monotonic()-started, 3),
'containers': [json.loads(x) for x in proc.stdout.splitlines() if x]})
end.wait(1)
def status():
return [{'service': s, 'id': data['Id'][:12], 'instance': data['Config']['Hostname'],
'running': data['State']['Running'], 'image': data['Image']}
for s in manage.SERVICES for data in map(manage.inspect, manage.containers(s))]
before = status()
monitor = threading.Thread(target=stats, daemon=True)
action_at = action_done = None
hook_output = ''
action_error = None
with ThreadPoolExecutor(max_workers=4) as pool:
jobs = [pool.submit(load, i) for i in range(4)]
workload_started.wait()
monitor.start()
try:
time.sleep(3) # Same warm-up for each scenario.
action_at = time.monotonic()-started
if service:
container = manage.containers(service)[0]
target = manage.inspect(container)['Config']['Hostname']
env = dict(os.environ, TARGET_INSTANCE_ID=target)
proc = subprocess.run([str(ROOT/'scripts/stop-one.sh')], cwd=ROOT, env=env,
capture_output=True, text=True, timeout=10)
else:
proc = subprocess.run([str(ROOT/'scripts/rolling-update.sh')], cwd=ROOT,
capture_output=True, text=True, timeout=180)
action_done = time.monotonic()-started
hook_output = proc.stdout + proc.stderr
check(proc.returncode == 0, 'action failed; inspect sanitized action log')
time.sleep(12 if service else 5)
except Exception as exc:
action_error = exc
finally:
end.set()
for job in jobs:
job.result()
monitor.join(timeout=15)
after = status()
history = whole_history(c, bob, chat)
by_text = {}
for item in history:
by_text.setdefault(item['text'], []).append(item)
missing = [text for text, msg in confirmations.items() if by_text.get(text) != [msg]]
duplicate_texts = sum(len(items)-1 for items in by_text.values())
check(by_text.get(seed['text']) == [seed], 'pre-action confirmed message lost')
check(c.message(alice, chat, seed['text'], key=seed_key)['json'] == seed, 'replay across action differs')
def summary(selected, elapsed):
successes = [e for e in selected if e['ok']]
latencies = sorted(e['elapsed'] * 1000 for e in successes)
def percentile(p):
return round(latencies[max(0, math.ceil(len(latencies)*p)-1)], 3) if latencies else None
return {'successful_requests': len(successes), 'failed_requests': len(selected)-len(successes),
'successful_rps': round(len(successes)/elapsed, 3) if elapsed else None,
'error_ratio': round(1-len(successes)/len(selected), 6) if selected else None,
'successful_latency_ms': {'p50': percentile(.5), 'p95': percentile(.95), 'p99': percentile(.99)}}
elapsed = time.monotonic()-started
recovery = {}
for kind in ('read', 'write'):
times = [e['at']-action_at for e in events if e['ok'] and e['kind']==kind and e['at']>=action_done]
recovery[kind] = round(min(times), 3) if times else None
success_gaps = {}
for kind in ('read', 'write'):
timeline = sorted(e['at'] for e in events if e['ok'] and e['kind']==kind)
# Include boundaries of the action, so silence during the entire action
# cannot be hidden by success only before or after it.
timeline = [action_at] + [t for t in timeline if action_at<=t<=(action_done or elapsed)] + [action_done or elapsed]
success_gaps[kind] = round(max(b-a for a,b in zip(timeline,timeline[1:])), 3)
report = {'scenario': 'stop-'+service if service else 'rolling-update', 'concurrency': 4,
'warmup_seconds': 3, 'elapsed_seconds': round(elapsed, 3),
'action_start_seconds': round(action_at, 3), 'action_done_seconds': round(action_done, 3) if action_done else None,
'first_success_after_action_from_action_start_seconds': recovery,
'before': before, 'after': after,
'http': summary(events, elapsed),
'read': summary([e for e in events if e['kind']=='read'], elapsed),
'write': summary([e for e in events if e['kind']=='write'], elapsed),
'during_action': summary([e for e in events if action_at<=e['at']<=(action_done or elapsed)], (action_done or elapsed)-action_at),
'confirmed_messages': len(confirmations), 'history_messages': len(history),
'missing_or_changed_confirmations': len(missing), 'duplicate_texts': duplicate_texts,
'resources': samples, 'maximum_gap_between_successes_during_action_seconds': success_gaps,
'note': 'Closed-loop, four writers alternate POST and GET. Percentiles cover successful HTTP requests only; retries preserve key/body. Recovery is first success after hook completion measured from hook start; not an outage duration. One Docker host; no node/DB/LB HA claim.'}
name = report['scenario']
(ROOT/'evidence'/('%s.json' % name)).write_text(json.dumps(report, ensure_ascii=False, indent=2)+'\n')
(ROOT/'evidence'/('%s-action.txt' % name)).write_text(hook_output)
check(action_error is None, 'action failed: %s' % action_error)
check(not missing and not duplicate_texts, 'lost/duplicated messages')
if service:
check(all(x is not None and x<=10 for x in recovery.values()), 'read/write recovery exceeded 10s')
target_entry = next(e for e in after if e['service']==service)
check(not target_entry['running'], 'target replica is still running')
recent_instances = {e.get('instance') for e in events if e['kind']=='write' and e['ok'] and e['at']>action_done+3}
check(target_entry['instance'] not in recent_instances, 'stopped target still serves writes')
else:
check(all(x<=3 for x in success_gaps.values()), 'rolling read/write availability gap exceeded 3 seconds')
for kind in ('read', 'write'):
for left in range(int(action_at), int(action_done), 3):
right = min(left+3, action_done)
check(any(e['ok'] and e['kind']==kind and left<=e['at']<=right for e in events),
'no successful %s during rolling window' % kind)
check(all(a['id']!=b['id'] for a,b in zip(before, after)), 'not every replica was replaced')
check(all(a['image']!=b['image'] for a,b in zip(before, after)), 'new image was not deployed')
print(json.dumps({k:v for k,v in report.items() if k not in ('resources','before','after','note')}, ensure_ascii=False))
print('PASS:', name)
def main():
def configure(p):
p.add_argument('--scenario', choices=('failover', 'rolling'), required=True)
args = arguments(__doc__, configure)
try:
if args.scenario == 'failover':
for service in manage.SERVICES:
manage.restore()
scenario(args, service)
else:
scenario(args)
finally:
manage.restore()
if __name__ == '__main__':
run(main)
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Cross-replica idempotency, key isolation, sessions and pagination."""
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import sys
import threading
import uuid
from urllib.parse import quote
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments(__doc__)
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/%s/messages' % chat['id']
observed = {c.call('GET', '/api/v1/users/me', actor=alice)['headers']['X-Instance-Id'] for _ in range(20)}
check(len(observed) >= 2, 'one session must work through at least two replicas')
key = uuid.uuid4().hex
barrier = threading.Barrier(12)
def worker(_):
local = Client(args.base_url, args.ca_file)
barrier.wait()
return local.message(alice, chat, 'Один ключ — одно сообщение 👋', key=key)
with ThreadPoolExecutor(max_workers=12) as pool:
replies = list(pool.map(worker, range(12)))
instances = {r['headers']['X-Instance-Id'] for r in replies}
check(len(instances) >= 2, 'parallel key replay did not reach both replicas')
first = replies[0]['json']
check(all(r['json'] == first and r['status'] == 201 for r in replies), 'replays differ')
page = c.call('GET', path, actor=alice, schema='MessagePage')['json']
check(page['items'] == [first], 'parallel replay stored duplicate messages')
c.call('POST', path, 409, actor=alice, body={'text': 'другое'}, headers={'Idempotency-Key': key})
for bad in (None, '', 'bad key', 'x' * 129, 'bad/key'):
c.call('POST', path, 400, actor=alice, body={'text': 'invalid'},
headers={} if bad is None else {'Idempotency-Key': bad})
c.call('POST', path, 404, actor=eve, body={'text': first['text']}, headers={'Idempotency-Key': key})
other_user = c.message(bob, chat, first['text'], key=key)['json']
check(other_user['id'] != first['id'], 'different user key was aliased')
second_chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json']
other_chat = c.message(alice, second_chat, first['text'], key=key)['json']
check(other_chat['id'] != first['id'], 'different chat key was aliased')
for index in range(5):
c.message(alice, chat, 'page-%d' % index)
result, cursor, page_instances = [], None, set()
while True:
url = path + '?limit=1' + (('&cursor=' + quote(cursor, safe='')) if cursor else '')
reply = c.call('GET', url, actor=alice, schema='MessagePage')
page_instances.add(reply['headers']['X-Instance-Id'])
result.extend(reply['json']['items'])
cursor = reply['json']['next_cursor']
if cursor is None:
break
check(len(result) == len({m['id'] for m in result}) == 7, 'pagination lost/duplicated messages')
check(len(page_instances) >= 2, 'cursor did not cross replicas')
# Revocation is observed on every API, even with an existing Redis entry.
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
for _ in range(8):
c.call('GET', '/api/v1/users/me', 401, actor=alice)
c.call('POST', path, 401, actor=alice, body={'text': first['text']}, headers={'Idempotency-Key': key})
print(json.dumps({'parallel_requests': 12, 'parallel_replicas': sorted(instances),
'unique_parallel_messages': 1, 'pagination_messages': 7,
'pagination_replicas': sorted(page_instances)}, ensure_ascii=False))
print('PASS: cross-replica idempotency, isolation, pagination and logout')
if __name__ == '__main__':
run(main)
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""A live but frozen API must be removed by active readiness, then restored."""
from pathlib import Path
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
import manage
container=manage.containers('api-a')[0]
started=time.monotonic()
try:
manage.command(['docker','pause',container])
while True:
config=manage.compose('exec','-T','nginx','cat','/etc/nginx/upstreams.conf',capture=True)
if any('api-a:' in line and ' down;' in line for line in config.splitlines()):
break
assert time.monotonic()-started < 5, 'readiness did not remove frozen backend within 5s'
time.sleep(.2)
print('PASS: frozen api-a excluded in %.3fs' % (time.monotonic()-started))
finally:
manage.command(['docker','unpause',container])
started=time.monotonic()
while True:
config=manage.compose('exec','-T','nginx','cat','/etc/nginx/upstreams.conf',capture=True)
if not any('api-a:' in line and ' down;' in line for line in config.splitlines()):
break
assert time.monotonic()-started<10, 'healthy backend did not return'
time.sleep(.2)
print('PASS: healthy backend restored in %.3fs' % (time.monotonic()-started))
manage.wait_healthy('api-a')
+354
View File
@@ -0,0 +1,354 @@
#!/usr/bin/env python3
"""Student-owned lab3 regression tests: sessions, validation, pagination.
One command: make student-test
Direct call: python3 student-tests/run.py --base-url http://localhost:8080
The suite complements tests/smoke.py and never weakens it. Every run creates
synthetic users, chats and messages only; no public check is imported or patched.
"""
from __future__ import annotations
import base64
import datetime as dt
import http.client
import json
import sys
import urllib.request
import uuid
from pathlib import Path
from urllib.parse import quote, urlsplit
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, LAB, arguments, check, timestamp # noqa: E402
if LAB != 3:
print('FAIL: student tests target lab3, but lab.json declares lab%d' % LAB)
raise SystemExit(2)
CHAT_PATH = '/api/v1/chats/%s'
class StudentClient(Client):
def call(self, method, path, *args, **kwargs):
if method == 'POST' and path.endswith('/messages'):
headers = dict(kwargs.get('headers') or {})
headers.setdefault('Idempotency-Key', uuid.uuid4().hex)
kwargs['headers'] = headers
return super().call(method, path, *args, **kwargs)
MESSAGES_PATH = CHAT_PATH + '/messages'
MAX_PAGES = 200
TESTS = []
def test(func):
TESTS.append(func)
return func
class Context:
"""Shared synthetic fixtures: three users, one chat between two of them."""
def __init__(self, client):
self.client = client
self.alice, self.bob, self.eve, self.chat = client.bootstrap()
def new_chat(self, title, members):
return self.client.call('POST', '/api/v1/chats', 201, actor=members[0],
body={'title': title,
'member_ids': [member['id'] for member in members]},
schema='Chat')['json']
def send(self, actor, chat, text):
return self.client.call('POST', MESSAGES_PATH % chat['id'], 201, actor=actor,
body={'text': text}, schema='Message')['json']
def page(self, actor, chat, limit, cursor=None):
query = '?limit=%d' % limit
if cursor is not None:
query += '&cursor=' + quote(cursor, safe='')
return self.client.call('GET', MESSAGES_PATH % chat['id'] + query, actor=actor,
schema='MessagePage')['json']
def traverse(self, actor, chat, limits):
"""Walk the whole history, changing the page size between requests."""
items, cursor, pages = [], None, 0
while True:
limit = limits[min(pages, len(limits) - 1)]
page = self.page(actor, chat, limit, cursor)
items.extend(page['items'])
cursor = page['next_cursor']
pages += 1
check(pages < MAX_PAGES, 'pagination did not terminate')
if cursor is None:
break
return items, pages
def ordered(records):
"""Contract order: (created_at, id) ascending, exactly as the client sorts."""
return sorted(records, key=lambda item: (timestamp(item['created_at']),
uuid.UUID(item['id']).int))
def traversal_order(records):
return [item['id'] for item in records]
# --------------------------------------------------------------------- health
@test
def health_and_request_id(ctx):
for path in ('/health/live', '/health/ready'):
result = ctx.client.call('GET', path, schema='Health')
check(result['json'] == {'status': 'ok'},
'%s must return exactly {"status":"ok"}' % path)
check(len(result['headers']['X-Request-Id']) >= 8, 'request id looks too short')
marker = 'student-' + uuid.uuid4().hex
echoed = ctx.client.call('GET', '/health/live', headers={'X-Request-Id': marker})
check(echoed['headers']['X-Request-Id'] == marker, 'client request id was not echoed')
error = ctx.client.call('GET', '/api/v1/users/me', 401, headers={'X-Request-Id': marker})
check(error['headers']['X-Request-Id'] == marker, 'error response lost the request id')
check(error['json']['error']['request_id'] == marker, 'error body request_id mismatch')
# -------------------------------------------------------------- unknown route
@test
def unknown_route_and_method_are_json_404(ctx):
ctx.client.call('GET', '/api/v1/unknown', 404)
ctx.client.call('DELETE', '/api/v1/chats', 404, actor=ctx.alice)
ctx.client.call('GET', '/api/v1/chats/', 404, actor=ctx.alice)
# --------------------------------------------------------------- user payload
@test
def malformed_json_is_rejected(ctx):
json_headers = {'Content-Type': 'application/json'}
ctx.client.call('POST', '/api/v1/users', 400, raw=b'{"username": "broken",', headers=json_headers)
ctx.client.call('POST', '/api/v1/users', 400, raw=b'[1, 2, 3]', headers=json_headers)
ctx.client.call('POST', '/api/v1/users', 400, raw=b'"just a string"', headers=json_headers)
ctx.client.call('POST', '/api/v1/users', 400, raw=b'', headers=json_headers)
ctx.client.call('POST', '/api/v1/users', 415, raw=b'{"username": "x"}',
headers={'Content-Type': 'text/plain'})
ctx.client.call('POST', '/api/v1/users', 415, raw=b'{"username": "x"}',
headers={'Content-Type': 'application/x-www-form-urlencoded'})
@test
def duplicate_username_is_409(ctx):
name = 'dup_' + uuid.uuid4().hex[:12]
body = {'username': name, 'display_name': 'Дубликат',
'password': 'T3st-' + uuid.uuid4().hex}
created = ctx.client.call('POST', '/api/v1/users', 201, body=body, schema='User')['json']
check(created['username'] == body['username'], 'username changed on creation')
conflict = ctx.client.call('POST', '/api/v1/users', 409, body=body)
check(conflict['json']['error']['code'] == 'conflict', 'duplicate username must be conflict')
@test
def user_payload_validation(ctx):
name = 'valid_' + uuid.uuid4().hex[:8]
for bad in (
{'username': name, 'display_name': 'Имя', 'password': 'ok', 'extra': 1},
{'display_name': 'Имя', 'password': 'ok'},
{'username': name, 'password': 'ok'},
{'username': name, 'display_name': ' ', 'password': 'ok'},
{'username': name, 'display_name': '', 'password': 'ok'},
{'username': name, 'display_name': 42, 'password': 'ok'},
{'username': name, 'display_name': None, 'password': 'ok'},
{'username': name, 'display_name': 'д' * 101, 'password': 'ok'},
{'username': 'AB', 'display_name': 'Имя', 'password': 'ok'},
{'username': 'with space', 'display_name': 'Имя', 'password': 'ok'},
{'username': 'юзер123', 'display_name': 'Имя', 'password': 'ok'},
{'username': 'x' * 33, 'display_name': 'Имя', 'password': 'ok'},
{'username': '', 'display_name': 'Имя', 'password': 'ok'},
{'username': 123, 'display_name': 'Имя', 'password': 'ok'},
# password too short
{'username': name, 'display_name': 'Имя', 'password': 'short'},
# password too long
{'username': name, 'display_name': 'Имя', 'password': 'д' * 129},
):
ctx.client.call('POST', '/api/v1/users', 400, body=bad)
ok = ctx.client.call('POST', '/api/v1/users', 201,
body={'username': name, 'display_name': 'Студент Юникод 👋',
'password': 'T3st-' + uuid.uuid4().hex},
schema='User')['json']
check(ok['display_name'] == 'Студент Юникод 👋', 'unicode display_name changed')
check('password' not in ok and 'token' not in ok, 'user projection leaks credentials')
# ------------------------------------------------------------- sessions
@test
def basic_login_issues_bearer_session(ctx):
reg = ctx.alice['registration']
credential = base64.b64encode((reg['username'] + ':' + reg['password']).encode()).decode()
session = ctx.client.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': 'Basic ' + credential},
schema='Session')['json']
check(session['user'] == ctx.alice['user'], 'session user mismatch')
check(session['token_type'] == 'Bearer', 'token type must be Bearer')
check(len(session['token']) >= 32, 'token must be opaque and long enough')
check(timestamp(session['expires_at']) > dt.datetime.now(dt.timezone.utc),
'session already expired')
ctx.alice['token'] = session['token']
# wrong password -> 401
bad = base64.b64encode((reg['username'] + ':wrong-password').encode()).decode()
ctx.client.call('POST', '/api/v1/auth/sessions', 401,
headers={'Authorization': 'Basic ' + bad})
# unknown user -> 401
bad = base64.b64encode(('nonexistent-user:' + reg['password']).encode()).decode()
ctx.client.call('POST', '/api/v1/auth/sessions', 401,
headers={'Authorization': 'Basic ' + bad})
@test
def bearer_required_for_business_endpoints(ctx):
# no auth -> 401
ctx.client.call('GET', '/api/v1/users/me', 401)
# Basic on business endpoint -> 401
reg = ctx.alice['registration']
credential = base64.b64encode((reg['username'] + ':' + reg['password']).encode()).decode()
ctx.client.call('GET', '/api/v1/users/me', 401,
headers={'Authorization': 'Basic ' + credential})
# X-User-Id ignored -> 401
ctx.client.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': ctx.alice['id']})
# Bearer works
me = ctx.client.call('GET', '/api/v1/users/me', 200, actor=ctx.alice,
schema='User')['json']
check(me == ctx.alice['user'], 'current user mismatch')
@test
def logout_revokes_session(ctx):
reg = ctx.alice['registration']
credential = base64.b64encode((reg['username'] + ':' + reg['password']).encode()).decode()
session = ctx.client.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': 'Basic ' + credential},
schema='Session')['json']
token = session['token']
ctx.client.call('DELETE', '/api/v1/auth/sessions/current', 204,
headers={'Authorization': 'Bearer ' + token})
# revoked token -> 401
ctx.client.call('GET', '/api/v1/users/me', 401,
headers={'Authorization': 'Bearer ' + token})
ctx.client.call('DELETE', '/api/v1/auth/sessions/current', 401,
headers={'Authorization': 'Bearer ' + token})
# -------------------------------------------------------------- message rules
@test
def foreign_chat_is_invisible(ctx):
other = ctx.new_chat('Чат без Евы', [ctx.alice, ctx.bob])
ctx.client.call('GET', CHAT_PATH % other['id'], 404, actor=ctx.eve)
ctx.client.call('GET', MESSAGES_PATH % other['id'], 404, actor=ctx.eve)
ctx.client.call('POST', MESSAGES_PATH % other['id'], 404, actor=ctx.eve,
body={'text': 'чужое сообщение'})
listed = ctx.client.call('GET', '/api/v1/chats?limit=100', actor=ctx.eve,
schema='ChatPage')['json']
check(all(item['id'] != other['id'] for item in listed['items']),
'foreign chat leaked into the list of another user')
member_view = ctx.client.call('GET', '/api/v1/chats?limit=100', actor=ctx.bob,
schema='ChatPage')['json']
check(any(item['id'] == other['id'] for item in member_view['items']),
'member cannot see the own chat')
ctx.client.call('GET', CHAT_PATH % uuid.uuid4(), 404, actor=ctx.alice)
ctx.client.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=ctx.alice)
ctx.client.call('GET', MESSAGES_PATH % 'not-a-uuid', 400, actor=ctx.alice)
@test
def message_payload_validation(ctx):
"""Empty and whitespace-only text is rejected."""
for bad in (
{'text': ''},
{'text': ' '},
{'text': '\u00a0\t\n'},
{},
{'text': 123},
{'text': None},
{'text': []},
{'text': 'ок', 'sender_id': ctx.bob['id']},
{'text': 'д' * 4001},
):
ctx.client.call('POST', MESSAGES_PATH % ctx.chat['id'], 400, actor=ctx.alice, body=bad)
ctx.client.call('POST', MESSAGES_PATH % ctx.chat['id'], 401, body={'text': 'ок'})
ctx.client.call('POST', MESSAGES_PATH % ctx.chat['id'], 400, actor=ctx.alice, raw=b'{"text":}',
headers={'Content-Type': 'application/json'})
ctx.client.call('POST', MESSAGES_PATH % ctx.chat['id'], 415, actor=ctx.alice,
raw=b'{"text":"ok"}', headers={'Content-Type': 'application/xml'})
@test
def text_limits_and_unicode_roundtrip(ctx):
longest = 'д' * 3999 + '👋'
check(len(longest) == 4000, 'fixture must be exactly 4000 code points')
created = ctx.send(ctx.bob, ctx.chat, longest)
check(created['text'] == longest, '4000 code points text changed')
check(created['sender_id'] == ctx.bob['id'], 'sender must be derived from actor')
mixed = 'Привет 👋🏽 \u00a0 e\u0301 — астральные 🚀🧪 и кавычки «»'
echo = ctx.send(ctx.alice, ctx.chat, mixed)
check(echo['text'] == mixed, 'mixed unicode text changed in transit')
check(echo['chat_id'] == ctx.chat['id'], 'message bound to the wrong chat')
# ---------------------------------------------------------------- pagination
@test
def multi_page_traversal_is_exact_and_stable(ctx):
chat = ctx.new_chat('Пагинация', [ctx.bob, ctx.alice])
sent = []
for index in range(7):
actor = ctx.alice if index % 2 == 0 else ctx.bob
sent.append(ctx.send(actor, chat, 'страница-%d-👋' % index))
expected = traversal_order(ordered(sent))
walked, pages = ctx.traverse(ctx.bob, chat, [2])
check(pages >= 4, 'seven messages with limit=2 must take at least four pages')
check(traversal_order(walked) == expected, 'traversal lost, duplicated or reordered messages')
check(len(set(traversal_order(walked))) == len(walked), 'traversal returned duplicates')
switched, _ = ctx.traverse(ctx.alice, chat, [2, 3, 1])
check(traversal_order(switched) == expected, 'changing limit mid-traversal changed the order')
singles, _ = ctx.traverse(ctx.alice, chat, [1])
check(len(singles) == 7, 'limit=1 traversal must return all seven messages')
first = ctx.page(ctx.alice, chat, 2)
check(len(first['items']) == 2 and first['next_cursor'], 'first page shape is wrong')
check(first['items'][0]['id'] == expected[0], 'first page must start with the oldest message')
@test
def default_page_limit_is_fifty(ctx):
chat = ctx.new_chat('Предел страницы по умолчанию', [ctx.alice, ctx.bob])
for index in range(51):
ctx.send(ctx.alice, chat, 'default-limit-%d' % index)
page = ctx.client.call('GET', MESSAGES_PATH % chat['id'], actor=ctx.alice,
schema='MessagePage')['json']
check(len(page['items']) == 50, 'default limit must be 50, got %d' % len(page['items']))
check(page['next_cursor'], 'a page that is not the last one needs a cursor')
tail = ctx.page(ctx.alice, chat, 100, page['next_cursor'])
check(len(tail['items']) == 1, 'the remaining page must hold exactly one message')
check(tail['next_cursor'] is None, 'last page must have next_cursor null')
merged = traversal_order(page['items']) + traversal_order(tail['items'])
check(len(set(merged)) == 51, 'page boundaries duplicated or dropped messages')
def main():
args = arguments('Student-owned lab3 regression tests: sessions, validation, pagination')
client = StudentClient(args.base_url, args.ca_file)
ctx = Context(client)
print('student-tests: %d cases against %s' % (len(TESTS), client.base))
failures = []
for func in TESTS:
try:
func(ctx)
except (Failure, ValueError, OSError) as exc:
failures.append(func.__name__)
print('FAIL %-42s %s' % (func.__name__, exc))
else:
print('PASS %-42s' % func.__name__)
print('%d passed, %d failed' % (len(TESTS) - len(failures), len(failures)))
return 1 if failures else 0
if __name__ == '__main__':
raise SystemExit(main())
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Run inside API image: real SQL rollback, idempotency atomicity and index evidence."""
from pathlib import Path
import sys
import uuid
sys.path.insert(0, '/app/src')
from messenger.cache import SessionCache
from messenger.config import Config
from messenger.db import Database
from messenger.errors import InvalidRequest
from messenger.security import hash_password
from messenger.store import Store
def main():
config = Config.from_env()
db = Database(config)
db.open()
store = Store(config, db, SessionCache(config))
suffix = uuid.uuid4().hex[:10]
actor = store.create_user('sql_' + suffix, 'SQL synthetic', hash_password('test-password-123'))
try:
with db.cursor() as cur:
cur.execute('SELECT count(*) AS n FROM chats')
before = cur.fetchone()['n']
try:
store.create_chat('Must rollback', [actor['id'], str(uuid.uuid4())])
raise AssertionError('unknown member was accepted')
except InvalidRequest:
pass
with db.cursor() as cur:
cur.execute('SELECT count(*) AS n FROM chats')
assert cur.fetchone()['n'] == before, 'partial chat survived rollback'
print('PASS: actual multi-statement chat transaction rollback')
chat = store.create_chat('SQL test', [actor['id']])
function = 'test_reject_' + suffix
key = 'rollback-' + suffix
# Simulate failure between message INSERT and idempotency result INSERT.
# Unique function/key isolate this synthetic test from every other request.
with db.cursor() as cur:
cur.execute("CREATE FUNCTION " + function + "() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN "
"IF NEW.key = '" + key + "' THEN RAISE EXCEPTION 'synthetic rollback'; END IF; RETURN NEW; END $$")
cur.execute('CREATE TRIGGER ' + function + ' BEFORE INSERT ON message_idempotency '
'FOR EACH ROW EXECUTE FUNCTION ' + function + '()')
try:
try:
store.add_message(chat['id'], actor['id'], 'must rollback', key)
raise AssertionError('injected failure did not occur')
except Exception as exc:
assert 'synthetic rollback' in str(exc), type(exc).__name__
with db.cursor() as cur:
cur.execute('SELECT count(*) AS n FROM messages WHERE chat_id=%s', (chat['id'],))
assert cur.fetchone()['n'] == 0, 'message committed without replay record'
finally:
with db.cursor() as cur:
cur.execute('DROP TRIGGER ' + function + ' ON message_idempotency')
cur.execute('DROP FUNCTION ' + function + '()')
message = store.add_message(chat['id'], actor['id'], 'must rollback', key)
assert store.add_message(chat['id'], actor['id'], 'must rollback', key) == message
print('PASS: message/result atomic rollback; same key usable after transient failure')
with db.cursor() as cur:
cur.execute('INSERT INTO messages(id,chat_id,sender_id,text,created_at) '
"SELECT gen_random_uuid(),%s,%s,'index-'||g, '2026-01-01'::timestamptz+g*interval '1 second' "
'FROM generate_series(1,10000) AS g', (chat['id'], actor['id']))
cur.execute('ANALYZE messages')
cur.execute('EXPLAIN (ANALYZE, BUFFERS) SELECT id,chat_id,sender_id,text,created_at '
'FROM messages WHERE chat_id=%s ORDER BY created_at,id LIMIT 51', (chat['id'],))
plan = '\n'.join(row['QUERY PLAN'] for row in cur.fetchall())
assert 'idx_messages_chat_created_id' in plan and 'Index Scan' in plan, plan
print(plan)
print('PASS: history index on at least 10000 messages')
db.run_migrations()
db.run_migrations()
with db.cursor() as cur:
cur.execute('SELECT name FROM schema_migrations ORDER BY name')
assert [r['name'] for r in cur.fetchall()] == ['0001_init.sql', '0002_idempotency.sql']
cur.execute('SELECT count(*) AS n FROM messages WHERE chat_id=%s', (chat['id'],))
assert cur.fetchone()['n'] == 10001
print('PASS: repeated versioned migrations preserved existing messages')
finally:
db.close()
if __name__ == '__main__':
main()
+77
View File
@@ -0,0 +1,77 @@
"""Regression tests for password compatibility and HTTP framing/drain."""
import hashlib
import http.client
import logging
from pathlib import Path
import sys
import threading
import unittest
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from messenger import security
from messenger.config import Config
from messenger.server import ApiServer
from messenger.validation import require_idempotency_key
from messenger.errors import InvalidRequest
class IdempotencyValidationTests(unittest.TestCase):
def test_key_format(self):
for value in ('abc', 'A-Z_0.1:key', 'x' * 128):
self.assertEqual(require_idempotency_key(value), value)
for value in (None, '', 'x' * 129, 'a b', 'ключ', 'a\n'):
with self.assertRaises(InvalidRequest):
require_idempotency_key(value)
class PasswordTests(unittest.TestCase):
@unittest.skipUnless(hasattr(hashlib, 'scrypt'), 'host Python lacks scrypt; run in API image')
def test_native_scrypt_is_used_and_can_be_verified(self):
encoded = security.hash_password('test-password-123')
self.assertTrue(encoded.startswith('scrypt:'), encoded.split(':')[0])
self.assertTrue(security.verify_password('test-password-123', encoded))
def test_password_roundtrip(self):
for password in ('test-password-123', 'Я' * 100):
hashed = security.hash_password(password)
self.assertTrue(security.verify_password(password, hashed))
self.assertFalse(security.verify_password(password + 'x', hashed))
def test_bcrypt_hash_remains_readable_when_scrypt_available(self):
import bcrypt
encoded = 'bcrypt:' + bcrypt.hashpw(hashlib.sha256(b'test-password-123').digest(), bcrypt.gensalt(4)).decode()
with patch.object(security, '_HAS_SCRYPT', True):
self.assertTrue(security.verify_password('test-password-123', encoded))
class HTTPTests(unittest.TestCase):
def test_persistent_response_has_length_and_instance_id(self):
class API:
def dispatch(self, request):
return 200, {'status': 'ok'}
config = Config.from_env({'CURSOR_SECRET': 'shared'})
server = ApiServer(('127.0.0.1', 0), API(), config, logging.getLogger('test'), None)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
conn = http.client.HTTPConnection(*server.server_address, timeout=1)
conn.request('GET', '/health/live')
response = conn.getresponse()
self.assertIsNotNone(response.getheader('Content-Length'))
instance = response.getheader('X-Instance-Id')
self.assertTrue(instance)
self.assertEqual(response.read(), b'{"status":"ok"}')
conn.request('GET', '/health/live')
response = conn.getresponse()
self.assertEqual(response.getheader('X-Instance-Id'), instance)
response.read()
conn.close()
finally:
server.shutdown()
server.server_close()
thread.join()
if __name__ == '__main__':
unittest.main()