forked from mtusi2026/mtusi2026lab2
126 lines
5.3 KiB
Python
126 lines
5.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Focused lab2 grade-4 checks; requires the local Compose stack and 2-second TTL."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import base64
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
import subprocess
|
|
import time
|
|
import uuid
|
|
|
|
from client import Client, Failure, arguments, check, run, timestamp
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def compose(*args):
|
|
return subprocess.run(
|
|
['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
|
|
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
|
)
|
|
|
|
|
|
def chat_count() -> int:
|
|
result = compose(
|
|
'exec', '-T', 'postgres', 'sh', '-c',
|
|
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atqc "SELECT count(*) FROM chats"',
|
|
)
|
|
return int(result.stdout.strip())
|
|
|
|
|
|
def wait_ready(client: Client, timeout: float = 30) -> None:
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
client.call('GET', '/health/ready')
|
|
return
|
|
except Failure:
|
|
time.sleep(0.25)
|
|
raise Failure('API did not become ready after restoring a dependency')
|
|
|
|
|
|
def main():
|
|
args = arguments('Lab2 grade-4 checks against the local Compose stack')
|
|
c = Client(args.base_url, args.ca_file, timeout=8)
|
|
wait_ready(c)
|
|
|
|
# Concurrent requests for one username must have one winner and conflict losers.
|
|
race_name = 'u_race_' + uuid.uuid4().hex[:12]
|
|
race_body = {
|
|
'username': race_name, 'display_name': 'Concurrent registration',
|
|
'password': 'Concurrent-test-password-42',
|
|
}
|
|
def register_once(_):
|
|
local = Client(args.base_url, args.ca_file, timeout=5)
|
|
return local.call('POST', '/api/v1/users', expected=[201, 409], body=race_body)['status']
|
|
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
statuses = list(pool.map(register_once, range(8)))
|
|
check(statuses.count(201) == 1 and statuses.count(409) == 7,
|
|
'same-username race must produce one user and seven conflicts')
|
|
print('PASS: concurrent username registration (1 x 201, 7 x 409)')
|
|
|
|
actor = c.user('rollback')
|
|
bad_password = base64.b64encode(
|
|
(actor['registration']['username'] + ':incorrect-password').encode()
|
|
).decode()
|
|
c.call('POST', '/api/v1/auth/sessions', 401,
|
|
headers={'Authorization': 'Basic ' + bad_password})
|
|
print('PASS: invalid password returns 401')
|
|
|
|
before = chat_count()
|
|
unknown_id = str(uuid.uuid4())
|
|
c.call('POST', '/api/v1/chats', 400, actor=actor,
|
|
body={'title': 'Rollback probe', 'member_ids': [actor['id'], unknown_id]})
|
|
after = chat_count()
|
|
check(after == before, 'failed chat creation left a partial chat row')
|
|
print('PASS: failed chat creation rolled back chat and memberships')
|
|
|
|
# Keep a current token in memory only; outage checks use readiness and must fail closed.
|
|
outage_user = c.user('outage')
|
|
outage_basic = 'Basic ' + base64.b64encode((outage_user['registration']['username'] + ':' + outage_user['registration']['password']).encode()).decode()
|
|
compose('stop', 'redis')
|
|
try:
|
|
redis_ready = c.call('GET', '/health/ready', 503)
|
|
check(redis_ready['json']['error']['code'] == 'unavailable', 'Redis readiness error must be bounded')
|
|
redis_failure = c.call('POST', '/api/v1/auth/sessions', 503, headers={'Authorization': outage_basic})
|
|
check(redis_failure['json']['error']['code'] == 'unavailable', 'Redis failure must return a bounded 503')
|
|
finally:
|
|
compose('start', 'redis')
|
|
wait_ready(c)
|
|
print('PASS: Redis outage returns bounded 503 for readiness and session creation; service recovers')
|
|
|
|
compose('stop', 'postgres')
|
|
try:
|
|
db_ready = c.call('GET', '/health/ready', 503)
|
|
check(db_ready['json']['error']['code'] == 'unavailable', 'PostgreSQL readiness error must be bounded')
|
|
db_failure = c.call('POST', '/api/v1/users', 503, body={
|
|
'username': 'u_dbdown_' + uuid.uuid4().hex[:12],
|
|
'display_name': 'Unavailable database probe',
|
|
'password': 'Database-unavailable-test-42',
|
|
})
|
|
check(db_failure['json']['error']['code'] == 'unavailable', 'PostgreSQL failure must return a bounded 503')
|
|
finally:
|
|
compose('start', 'postgres')
|
|
wait_ready(c)
|
|
print('PASS: PostgreSQL outage returns bounded 503 for readiness and registration; service recovers')
|
|
|
|
# Expiry is checked last because all sessions in this run have a two-second TTL.
|
|
expiring = c.user('expiry')
|
|
c.call('GET', '/api/v1/users/me', actor=expiring)
|
|
session_response = c.call(
|
|
'POST', '/api/v1/auth/sessions', 201,
|
|
headers={'Authorization': 'Basic ' + base64.b64encode(
|
|
(expiring['registration']['username'] + ':' + expiring['registration']['password']).encode()
|
|
).decode()}, schema='Session',
|
|
)
|
|
expires_at = timestamp(session_response['json']['expires_at'])
|
|
remaining = (expires_at - datetime.now(timezone.utc)).total_seconds()
|
|
check(0 < remaining <= 2.5, 'session did not receive the configured two-second TTL')
|
|
time.sleep(remaining + 0.15)
|
|
c.call('GET', '/api/v1/users/me', 401, actor={'token': session_response['json']['token']})
|
|
print('PASS: Redis session expires at the original short TTL')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
run(main)
|