#!/usr/bin/env python3 """In-memory lifecycle demo: a container restart erases all lab1 state. Command (evidence/README.md keeps the text output, not screenshots): python3 scripts/lifecycle-demo.py --container mtusi-messenger-lab1 \ --output evidence/lifecycle.txt """ from __future__ import annotations import argparse import json import subprocess import sys import time import urllib.error import urllib.request import uuid def api(method, url, body=None, user_id=None, timeout=10): data = None if body is None else json.dumps(body).encode('utf-8') request = urllib.request.Request(url, data=data, method=method) request.add_header('Accept', 'application/json') if data is not None: request.add_header('Content-Type', 'application/json') if user_id: request.add_header('X-User-Id', user_id) try: with urllib.request.urlopen(request, timeout=timeout) as response: return response.status, json.loads(response.read().decode('utf-8')) except urllib.error.HTTPError as error: raw = error.read() try: payload = json.loads(raw.decode('utf-8')) except ValueError: payload = {'unparsed': raw[:200].decode('utf-8', 'replace')} return error.code, payload def docker(*args): result = subprocess.run(['docker', *args], capture_output=True, text=True) if result.returncode != 0: raise SystemExit('docker %s failed: %s%s' % (' '.join(args), result.stdout.strip(), result.stderr.strip())) return result.stdout.strip() def wait_ready(base_url, seconds=30): deadline = time.monotonic() + seconds while time.monotonic() < deadline: try: status, _payload = api('GET', base_url + '/health/ready', timeout=2) if status == 200: return True except OSError: pass time.sleep(0.3) return False def main(): parser = argparse.ArgumentParser(description='lab1 restart demo') parser.add_argument('--base-url', default='http://localhost:8080') parser.add_argument('--container', default='mtusi-messenger-lab1') parser.add_argument('--output', default=None) args = parser.parse_args() base = args.base_url.rstrip('/') lines = [] def say(text): print(text) lines.append(text) say('== lab1 lifecycle demo: state is process-local ==') say('container: %s api: %s' % (args.container, base)) if not wait_ready(base): raise SystemExit('FAIL: API is not ready at ' + base) before_running = docker('inspect', '--format', '{{.State.Status}}', args.container) say('container state before: %s' % before_running) username = 'life_' + uuid.uuid4().hex[:8] status, user = api('POST', base + '/api/v1/users', {'username': username, 'display_name': 'Демо lifecycle'}) say('1. POST /users -> %d (id=%s)' % (status, user.get('id'))) status, chat = api('POST', base + '/api/v1/chats', {'title': 'Демо-чат', 'member_ids': [user['id']]}, user_id=user['id']) say('2. POST /chats -> %d (id=%s)' % (status, chat.get('id'))) status, message = api('POST', base + '/api/v1/chats/%s/messages' % chat['id'], {'text': 'Сообщение переживает только процесс'}, user_id=user['id']) say('3. POST /messages -> %d (id=%s)' % (status, message.get('id'))) status, history = api('GET', base + '/api/v1/chats/%s/messages' % chat['id'], user_id=user['id']) say('4. GET /messages -> %d, messages in history: %d' % (status, len(history['items']))) status, me = api('GET', base + '/api/v1/users/me', user_id=user['id']) say('5. GET /users/me -> %d (username=%s)' % (status, me.get('username'))) say('6. docker restart %s' % args.container) started = time.monotonic() docker('restart', args.container) if not wait_ready(base): raise SystemExit('FAIL: API did not become ready after restart') say(' ready again after %.2f s' % (time.monotonic() - started)) identity_status, payload = api('GET', base + '/api/v1/users/me', user_id=user['id']) say('7. GET /users/me with the previous X-User-Id -> %d (%s)' % (identity_status, payload.get('error', {}).get('code'))) chat_status, chat_payload = api('GET', base + '/api/v1/chats/%s' % chat['id'], user_id=user['id']) say('8. GET /chats/{id} with the previous X-User-Id -> %d (%s)' % (chat_status, chat_payload.get('error', {}).get('code'))) recreate_status, again = api('POST', base + '/api/v1/users', {'username': username, 'display_name': 'Демо lifecycle'}) say('9. POST /users with the same username -> %d (new id=%s, old=%s)' % (recreate_status, again.get('id'), user['id'])) checks = [ (history['items'][0]['id'] == message['id'], 'message was readable before restart'), (identity_status == 401, 'previous identity is rejected with 401 after restart'), (chat_status == 401, 'previous chat is unreachable with the previous identity'), (payload.get('error', {}).get('code') == 'unauthorized', 'error code is unauthorized'), (recreate_status == 201, 'username is free again after restart'), (again.get('id') != user['id'], 'identity really changed'), ] failed = [text for ok, text in checks if not ok] say('RESULT: %s' % ('PASS — the previous user and chat are gone after restart' if not failed else 'FAIL — ' + '; '.join(failed))) if args.output: with open(args.output, 'w', encoding='utf-8') as handle: handle.write('\n'.join(lines) + '\n') return 1 if failed else 0 if __name__ == '__main__': sys.exit(main())