diff --git a/Makefile b/Makefile index 9ecb223e..d1829460 100644 --- a/Makefile +++ b/Makefile @@ -24,3 +24,11 @@ load: test-persistence: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +.PHONY: run migrate student-test +run: + $(PYTHON) -m messenger +migrate: + $(PYTHON) -m messenger.migrate +student-test: + $(PYTHON) -m unittest discover -s student-tests -v diff --git a/messenger/__init__.py b/messenger/__init__.py new file mode 100644 index 00000000..bd3057eb --- /dev/null +++ b/messenger/__init__.py @@ -0,0 +1 @@ +"""Messenger lab series.""" diff --git a/messenger/__main__.py b/messenger/__main__.py new file mode 100644 index 00000000..1402c9d3 --- /dev/null +++ b/messenger/__main__.py @@ -0,0 +1,15 @@ +import logging +from waitress import serve +from .api import create_app +from .config import Settings + + +def main(): + logging.basicConfig(level=logging.INFO) + settings = Settings.from_env() + logging.info('Starting messenger environment=%s', settings.environment) + serve(create_app(settings=settings), host=settings.host, port=settings.port, threads=4) + + +if __name__ == '__main__': + main() diff --git a/messenger/api.py b/messenger/api.py new file mode 100644 index 00000000..dec18818 --- /dev/null +++ b/messenger/api.py @@ -0,0 +1,115 @@ +"""HTTP adapter and composition root.""" +import json +from uuid import uuid4 +from flask import Flask, g, request, jsonify +from werkzeug.exceptions import HTTPException +from .domain import ApiError, invalid +from .postgres import PostgresRepository +from .database import Database +from .config import Settings +from .service import Messenger + + +def create_app(repository=None, settings=None): + app = Flask(__name__) + app.json.ensure_ascii = False + settings = settings or Settings.from_env() + repository = repository if repository is not None else PostgresRepository(Database(settings.database_url)) + service = Messenger(repository, settings.session_ttl) + + @app.before_request + def identify(): + g.request_id = str(uuid4()) + if request.path.startswith('/api/v1/') and not ( + request.path in ('/api/v1/users', '/api/v1/auth/sessions') and request.method == 'POST' + ): + g.user, g.token_hash = service.auth.bearer(request.headers.get('Authorization')) + + @app.after_request + def request_id(response): + response.headers['X-Request-Id'] = g.request_id + return response + + @app.errorhandler(Exception) + def error(exc): + if isinstance(exc, ApiError): + status, code, message = exc.status, exc.code, exc.message + elif isinstance(exc, HTTPException): + status = exc.code + code = {404: 'not_found', 413: 'payload_too_large', 415: 'unsupported_media_type'}.get(status, 'invalid_request') + message = exc.name + else: + app.logger.error('Unhandled error; request_id=%s', g.request_id) + status, code, message = 500, 'internal_error', 'Internal server error' + response = jsonify(error={'code': code, 'message': message, 'request_id': g.request_id}) + response.status_code = status + if status == 401: + response.headers['WWW-Authenticate'] = ( + 'Basic realm="messenger", charset="UTF-8"' + if request.path == '/api/v1/auth/sessions' and request.method == 'POST' + else 'Bearer realm="messenger"') + return response + + def body(): + if request.mimetype != 'application/json': + raise ApiError(415, 'unsupported_media_type', 'Use application/json') + try: + def reject_constant(value): + raise ValueError(value) + return json.loads(request.get_data().decode('utf-8'), parse_constant=reject_constant) + except (ValueError, UnicodeError): + invalid('Malformed UTF-8 JSON') + + def paging(): + for key in ('limit', 'cursor'): + if len(request.args.getlist(key)) > 1: + invalid('Duplicate query parameter') + return request.args.get('limit', '50'), request.args.get('cursor') + + @app.get('/health/live') + def health(): + return jsonify(status='ok') + + @app.get('/health/ready') + def ready(): + repository.ready() + return jsonify(status='ok') + + @app.post('/api/v1/auth/sessions') + def login(): + # Session creation accepts no request body. + if request.get_data(): + invalid('Session creation does not accept a body') + return jsonify(service.auth.login(request.headers.get('Authorization'))), 201 + + @app.delete('/api/v1/auth/sessions/current') + def logout(): + repository.revoke_session(g.token_hash) + return '', 204 + + @app.post('/api/v1/users') + def register(): + return jsonify(service.register(body())), 201 + + @app.get('/api/v1/users/me') + def me(): + return jsonify(g.user) + + @app.route('/api/v1/chats', methods=['GET', 'POST']) + def chats(): + if request.method == 'POST': + return jsonify(service.create_chat(g.user['id'], body())), 201 + return jsonify(service.chats(g.user['id'], *paging())) + + @app.get('/api/v1/chats/') + def chat(chat_id): + return jsonify(service.chat(g.user['id'], chat_id)) + + @app.route('/api/v1/chats//messages', methods=['GET', 'POST']) + def messages(chat_id): + if request.method == 'POST': + service.chat(g.user['id'], chat_id) + return jsonify(service.send(g.user['id'], chat_id, body())), 201 + return jsonify(service.history(g.user['id'], chat_id, *paging())) + + return app diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..7faec4b2 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,13 @@ +Flask==3.1.0 +waitress==3.0.2 +Werkzeug==3.1.3 +Jinja2==3.1.6 +MarkupSafe==3.0.3 +itsdangerous==2.2.0 +click==8.1.8 +blinker==1.9.0 +psycopg[binary]==3.2.6 +argon2-cffi==23.1.0 +argon2-cffi-bindings==21.2.0 +cffi==1.17.1 +pycparser==2.22