forked from mtusi2026/mtusi2026lab3
Implement lab3 grade 4: balanced API replicas, shared idempotency and failure tests
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Lab 1: bounded, single-process in-memory messenger."""
|
||||
@@ -0,0 +1,332 @@
|
||||
"""Validation and persistent state. HTTP 201 is emitted after transaction exit/COMMIT."""
|
||||
import base64
|
||||
from dataclasses import dataclass, fields
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import uuid
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import ConnectionPool
|
||||
import redis
|
||||
from redis.backoff import NoBackoff
|
||||
from redis.retry import Retry
|
||||
|
||||
|
||||
class APIError(Exception):
|
||||
def __init__(self, status, message):
|
||||
self.status, self.message = status, message
|
||||
|
||||
|
||||
@dataclass
|
||||
class Config:
|
||||
app_host: str = '0.0.0.0'
|
||||
app_port: int = 8080
|
||||
workers: int = 16
|
||||
request_queue: int = 32
|
||||
socket_timeout: int = 2
|
||||
max_body_bytes: int = 65536
|
||||
session_ttl_seconds: int = 3600
|
||||
idempotency_ttl_seconds: int = 86400
|
||||
|
||||
@classmethod
|
||||
def from_env(cls):
|
||||
values = {}
|
||||
for field in fields(cls):
|
||||
raw = os.environ.get(field.name.upper(), field.default)
|
||||
values[field.name] = str(raw) if field.type is str else int(raw)
|
||||
if field.type is int and values[field.name] < 1:
|
||||
raise ValueError(field.name + ' must be positive')
|
||||
result = cls(**values)
|
||||
if result.app_port > 65535 or result.workers > 32 or result.request_queue > 128:
|
||||
raise ValueError('port/workers/queue outside bounds')
|
||||
if result.max_body_bytes > 1048576 or result.socket_timeout > 5:
|
||||
raise ValueError('body <= 1 MiB and socket timeout <= 5 required')
|
||||
if os.getenv('SESSION_STORE', 'redis') != 'redis':
|
||||
raise ValueError('This solution uses Redis sessions')
|
||||
if result.idempotency_ttl_seconds < 86400:
|
||||
raise ValueError('Idempotency retention must be at least 24 hours')
|
||||
return result
|
||||
|
||||
|
||||
def secret_file(name):
|
||||
return Path(os.environ[name]).read_text(encoding='utf-8').strip()
|
||||
|
||||
|
||||
def db_connect_kwargs():
|
||||
return dict(connect_timeout=2, options='-c statement_timeout=2000 -c lock_timeout=1000 '
|
||||
'-c idle_in_transaction_session_timeout=5000', row_factory=dict_row)
|
||||
|
||||
|
||||
def uuid_value(value):
|
||||
if not isinstance(value, str) or not re.fullmatch(
|
||||
r'[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}', value):
|
||||
raise APIError(400, 'Invalid UUID')
|
||||
return str(uuid.UUID(value))
|
||||
|
||||
|
||||
def string(value, maximum):
|
||||
if not isinstance(value, str) or not value.strip() or len(value) > maximum or '\x00' in value:
|
||||
raise APIError(400, 'Invalid string')
|
||||
try:
|
||||
value.encode('utf-8')
|
||||
except UnicodeError:
|
||||
raise APIError(400, 'Invalid Unicode') from None
|
||||
return value
|
||||
|
||||
|
||||
def object_fields(body, expected):
|
||||
if not isinstance(body, dict) or set(body) != set(expected):
|
||||
raise APIError(400, 'Invalid object fields')
|
||||
|
||||
|
||||
def password_value(value):
|
||||
if not isinstance(value, str) or not value.strip() or not 12 <= len(value) <= 128:
|
||||
raise APIError(400, 'Invalid password length')
|
||||
try:
|
||||
value.encode('utf-8')
|
||||
except UnicodeError:
|
||||
raise APIError(400, 'Invalid Unicode') from None
|
||||
return value
|
||||
|
||||
|
||||
def password_hash(value, salt=None):
|
||||
salt = salt or secrets.token_bytes(16)
|
||||
digest = hashlib.scrypt(value.encode('utf-8'), salt=salt, n=16384, r=8, p=1, dklen=32)
|
||||
return 'scrypt$16384$8$1$' + salt.hex() + '$' + digest.hex()
|
||||
|
||||
|
||||
def password_matches(value, encoded):
|
||||
# Only this versioned format is generated by registration.
|
||||
salt = bytes.fromhex(encoded.split('$')[4])
|
||||
return hmac.compare_digest(password_hash(value, salt), encoded)
|
||||
|
||||
|
||||
def stamp(value):
|
||||
return value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def public_row(row):
|
||||
return {key: (str(value) if isinstance(value, uuid.UUID) else stamp(value)
|
||||
if isinstance(value, datetime) else value)
|
||||
for key, value in row.items() if key != 'password_hash'}
|
||||
|
||||
|
||||
USER_COLUMNS = 'id, username, display_name, created_at'
|
||||
MESSAGE_COLUMNS = 'id, chat_id, sender_id, text, created_at'
|
||||
# Shared by the real history endpoint and EXPLAIN evidence; all values are parameters.
|
||||
HISTORY_SQL = ('SELECT ' + MESSAGE_COLUMNS + ' FROM messages WHERE chat_id = %s '
|
||||
'AND (created_at, id) > (%s, %s) ORDER BY created_at, id LIMIT %s')
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
self.secret = bytes.fromhex(secret_file('CURSOR_KEY_FILE'))
|
||||
if len(self.secret) < 32:
|
||||
raise ValueError('Cursor key must be at least 256 bits')
|
||||
self.pool = ConnectionPool(secret_file('DATABASE_URL_FILE'), min_size=1, max_size=8,
|
||||
timeout=1, max_waiting=16, kwargs=db_connect_kwargs(),
|
||||
check=ConnectionPool.check_connection, open=True)
|
||||
self.cache_pool = redis.ConnectionPool.from_url(
|
||||
secret_file('CACHE_URL_FILE'), max_connections=8, socket_connect_timeout=.5,
|
||||
socket_timeout=.5, decode_responses=True, retry=Retry(NoBackoff(), 0))
|
||||
self.cache = redis.Redis(connection_pool=self.cache_pool)
|
||||
self.dummy_hash = password_hash('dummy-password-for-timing')
|
||||
|
||||
def close(self):
|
||||
self.pool.close(timeout=2)
|
||||
self.cache_pool.disconnect()
|
||||
|
||||
def ready(self):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute('SELECT 1')
|
||||
self.cache.ping()
|
||||
|
||||
def create_user(self, body):
|
||||
object_fields(body, ('username', 'display_name', 'password'))
|
||||
username = string(body['username'], 32)
|
||||
if not re.fullmatch(r'[a-z0-9_]{3,32}', username):
|
||||
raise APIError(400, 'Invalid username')
|
||||
display = string(body['display_name'], 100)
|
||||
hashed = password_hash(password_value(body['password']))
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('INSERT INTO users(id, username, display_name, password_hash) '
|
||||
'VALUES (%s,%s,%s,%s) RETURNING ' + USER_COLUMNS,
|
||||
(uuid.uuid4(), username, display, hashed)).fetchone()
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise APIError(409, 'Username already exists') from None
|
||||
return public_row(row)
|
||||
|
||||
def login(self, authorization):
|
||||
try:
|
||||
scheme, encoded = authorization.split(' ', 1)
|
||||
if scheme.lower() != 'basic' or len(encoded) > 1024:
|
||||
raise ValueError()
|
||||
username, password = base64.b64decode(encoded, validate=True).decode('utf-8').split(':', 1)
|
||||
if not re.fullmatch(r'[a-z0-9_]{3,32}', username):
|
||||
raise ValueError()
|
||||
password_value(password)
|
||||
except (AttributeError, ValueError, UnicodeError, APIError):
|
||||
raise APIError(401, 'Invalid credentials') from None
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT * FROM users WHERE username = %s', (username,)).fetchone()
|
||||
matched = password_matches(password, row['password_hash'] if row else self.dummy_hash)
|
||||
if not matched or row is None:
|
||||
raise APIError(401, 'Invalid credentials')
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_ms = int(datetime.now(timezone.utc).timestamp() * 1000) + self.config.session_ttl_seconds * 1000
|
||||
self.cache.set(self.session_key(token), str(row['id']), pxat=expires_ms)
|
||||
return dict(token=token, token_type='Bearer',
|
||||
expires_at=stamp(datetime.fromtimestamp(expires_ms / 1000, timezone.utc)),
|
||||
user=public_row(row))
|
||||
|
||||
@staticmethod
|
||||
def session_key(token):
|
||||
return 'session:' + hashlib.sha256(token.encode('ascii')).hexdigest()
|
||||
|
||||
def auth(self, header):
|
||||
try:
|
||||
scheme, token = header.split(' ', 1)
|
||||
if scheme.lower() != 'bearer' or not re.fullmatch(r'[A-Za-z0-9_-]{43}', token):
|
||||
raise ValueError()
|
||||
except (ValueError, AttributeError):
|
||||
raise APIError(401, 'Invalid session') from None
|
||||
key = self.session_key(token)
|
||||
actor = self.cache.get(key)
|
||||
if actor is None:
|
||||
raise APIError(401, 'Invalid session')
|
||||
return actor, key
|
||||
|
||||
def me(self, actor):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT ' + USER_COLUMNS + ' FROM users WHERE id = %s', (actor,)).fetchone()
|
||||
if row is None:
|
||||
raise APIError(401, 'Invalid session')
|
||||
return public_row(row)
|
||||
|
||||
def chat_access(self, actor, identifier):
|
||||
identifier = uuid_value(identifier)
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s',
|
||||
(identifier, actor)).fetchone()
|
||||
if row is None:
|
||||
raise APIError(404, 'Object not found')
|
||||
return identifier
|
||||
|
||||
@staticmethod
|
||||
def chat_row(conn, row):
|
||||
members = conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY position',
|
||||
(row['id'],)).fetchall()
|
||||
return dict(public_row(row), member_ids=[str(x['user_id']) for x in members])
|
||||
|
||||
def chat(self, chat_id):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT * FROM chats WHERE id=%s', (chat_id,)).fetchone()
|
||||
return self.chat_row(conn, row)
|
||||
|
||||
def create_chat(self, actor, body):
|
||||
object_fields(body, ('title', 'member_ids'))
|
||||
title = string(body['title'], 100)
|
||||
members = body['member_ids']
|
||||
if not isinstance(members, list) or not 1 <= len(members) <= 100:
|
||||
raise APIError(400, 'Invalid members')
|
||||
members = [uuid_value(x) for x in members]
|
||||
if len(members) != len(set(members)) or actor not in members:
|
||||
raise APIError(400, 'Invalid members')
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING *',
|
||||
(uuid.uuid4(), title)).fetchone()
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany('INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,%s)',
|
||||
[(row['id'], member, pos) for pos, member in enumerate(members)])
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
raise APIError(400, 'Invalid members') from None
|
||||
return dict(public_row(row), member_ids=members)
|
||||
|
||||
def create_message(self, actor, chat_id, body, key):
|
||||
if not isinstance(key, str) or not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key):
|
||||
raise APIError(400, 'One valid Idempotency-Key is required')
|
||||
if not isinstance(body, dict) or set(body) not in ({'text'}, {'text', 'attachment_ids'}):
|
||||
raise APIError(400, 'Invalid object fields')
|
||||
# Attachments start at lab4. Empty and omitted arrays are equivalent here.
|
||||
if 'attachment_ids' in body and body['attachment_ids'] != []:
|
||||
raise APIError(400, 'Attachments are not supported in lab3')
|
||||
text = string(body['text'], 4000)
|
||||
digest = hashlib.sha256(json.dumps({'text': text, 'attachment_ids': []},
|
||||
ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
||||
scope = json.dumps([actor, 'POST', '/api/v1/chats/' + chat_id + '/messages', key])
|
||||
lock = int.from_bytes(hashlib.sha256(scope.encode()).digest()[:8], 'big', signed=True)
|
||||
with self.pool.connection() as conn:
|
||||
# Transaction lock spans SELECT, message INSERT, result INSERT and COMMIT.
|
||||
# All replicas use PostgreSQL; a timeout rolls back and may be retried.
|
||||
conn.execute('SELECT pg_advisory_xact_lock(%s)', (lock,))
|
||||
previous = conn.execute('SELECT fingerprint, response, expires_at > clock_timestamp() AS valid '
|
||||
'FROM message_requests WHERE actor_id=%s AND chat_id=%s AND key=%s',
|
||||
(actor, chat_id, key)).fetchone()
|
||||
if previous and previous['valid']:
|
||||
if previous['fingerprint'] != digest:
|
||||
raise APIError(409, 'Idempotency-Key already used with another body')
|
||||
return previous['response']
|
||||
if previous:
|
||||
conn.execute('DELETE FROM message_requests WHERE actor_id=%s AND chat_id=%s AND key=%s',
|
||||
(actor, chat_id, key))
|
||||
row = conn.execute('INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) '
|
||||
'RETURNING ' + MESSAGE_COLUMNS, (uuid.uuid4(), chat_id, actor, text)).fetchone()
|
||||
result = public_row(row)
|
||||
conn.execute('INSERT INTO message_requests(actor_id,chat_id,key,fingerprint,response,expires_at) '
|
||||
"VALUES (%s,%s,%s,%s,%s,clock_timestamp() + %s * interval '1 second')",
|
||||
(actor, chat_id, key, digest, Jsonb(result), self.config.idempotency_ttl_seconds))
|
||||
return result
|
||||
|
||||
def encode_cursor(self, scope, key):
|
||||
payload = json.dumps([1, scope, *key], separators=(',', ':')).encode()
|
||||
return base64.urlsafe_b64encode(payload + hmac.digest(self.secret, payload, 'sha256')).rstrip(b'=').decode()
|
||||
|
||||
def decode_cursor(self, cursor, scope):
|
||||
try:
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]{1,1024}', cursor):
|
||||
raise ValueError()
|
||||
raw = base64.b64decode(cursor + '=' * (-len(cursor) % 4), altchars=b'-_', validate=True)
|
||||
if base64.urlsafe_b64encode(raw).rstrip(b'=').decode() != cursor:
|
||||
raise ValueError()
|
||||
payload, signature = raw[:-32], raw[-32:]
|
||||
if not hmac.compare_digest(signature, hmac.digest(self.secret, payload, 'sha256')):
|
||||
raise ValueError()
|
||||
version, resource, timestamp, identifier = json.loads(payload)
|
||||
if version != 1 or resource != scope or not isinstance(timestamp, str) or not timestamp.endswith('Z'):
|
||||
raise ValueError()
|
||||
return datetime.fromisoformat(timestamp.replace('Z', '+00:00')), uuid_value(identifier)
|
||||
except (ValueError, TypeError, UnicodeError, APIError):
|
||||
raise APIError(400, 'Invalid cursor') from None
|
||||
|
||||
def page(self, actor, chat_id, query):
|
||||
if set(query) - {'limit', 'cursor'} or any(len(v) != 1 for v in query.values()):
|
||||
raise APIError(400, 'Invalid query')
|
||||
limit = query.get('limit', ['50'])[0]
|
||||
if not re.fullmatch(r'[0-9]{1,3}', limit) or not 1 <= int(limit) <= 100:
|
||||
raise APIError(400, 'Invalid limit')
|
||||
limit = int(limit)
|
||||
scope = 'messages:' + chat_id if chat_id else 'chats:' + actor
|
||||
key = self.decode_cursor(query['cursor'][0], scope) if 'cursor' in query else (
|
||||
datetime.min.replace(tzinfo=timezone.utc), '00000000-0000-0000-0000-000000000000')
|
||||
with self.pool.connection() as conn:
|
||||
if chat_id:
|
||||
rows = conn.execute(HISTORY_SQL, (chat_id, *key, limit + 1)).fetchall()
|
||||
items = [public_row(row) for row in rows[:limit]]
|
||||
else:
|
||||
rows = conn.execute('SELECT c.* FROM chats c JOIN chat_members m ON m.chat_id=c.id '
|
||||
'WHERE m.user_id=%s AND (c.created_at,c.id) > (%s,%s) '
|
||||
'ORDER BY c.created_at,c.id LIMIT %s', (actor, *key, limit + 1)).fetchall()
|
||||
items = [self.chat_row(conn, row) for row in rows[:limit]]
|
||||
cursor = self.encode_cursor(scope, (items[-1]['created_at'], items[-1]['id'])) if len(rows) > limit else None
|
||||
return dict(items=items, next_cursor=cursor)
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Transactional, versioned migrations; repeat application is a no-op."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
from .core import secret_file, db_connect_kwargs
|
||||
|
||||
|
||||
def main():
|
||||
with psycopg.connect(secret_file('DATABASE_URL_FILE'), **db_connect_kwargs()) as conn:
|
||||
conn.execute('SELECT pg_advisory_xact_lock(2026, 2)')
|
||||
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations '
|
||||
'(name text PRIMARY KEY, sha256 text NOT NULL, '
|
||||
'applied_at timestamptz NOT NULL DEFAULT clock_timestamp())')
|
||||
for path in sorted((Path(__file__).resolve().parents[2] / 'migrations').glob('*.sql')):
|
||||
content = path.read_bytes()
|
||||
digest = hashlib.sha256(content).hexdigest()
|
||||
row = conn.execute('SELECT sha256 FROM schema_migrations WHERE name=%s', (path.name,)).fetchone()
|
||||
if row:
|
||||
if row['sha256'] != digest:
|
||||
raise RuntimeError('Applied migration checksum mismatch')
|
||||
print('Already applied:', path.name)
|
||||
continue
|
||||
conn.execute(content.decode('utf-8'), prepare=False)
|
||||
conn.execute('INSERT INTO schema_migrations(name,sha256) VALUES (%s,%s)', (path.name, digest))
|
||||
print('Applied:', path.name)
|
||||
print('Migrations committed.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,339 @@
|
||||
"""Bounded HTTP worker pool; one request per connection; JSON logs omit bodies."""
|
||||
from collections import Counter
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
import http.client
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import queue
|
||||
import signal
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
import uuid
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import PoolTimeout, TooManyRequests
|
||||
import redis
|
||||
|
||||
from .core import APIError, Config, Store
|
||||
|
||||
|
||||
CODES = {400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict",
|
||||
413: "payload_too_large", 415: "unsupported_media_type", 429: "rate_limited",
|
||||
503: "unavailable", 500: "internal_error"}
|
||||
|
||||
|
||||
def error_body(status, message, request_id):
|
||||
return {"error": {"code": CODES.get(status, "invalid_request"),
|
||||
"message": message, "request_id": request_id}}
|
||||
|
||||
|
||||
def log_event(**data):
|
||||
logging.info(json.dumps(data, ensure_ascii=True))
|
||||
|
||||
|
||||
class Server(HTTPServer):
|
||||
allow_reuse_address = True
|
||||
|
||||
def __init__(self, config):
|
||||
self.config, self.store = config, Store(config)
|
||||
self.instance_id = os.environ.get('HOSTNAME', 'api') + '-' + uuid.uuid4().hex[:12]
|
||||
self.jobs = queue.Queue(maxsize=config.request_queue)
|
||||
self.draining = threading.Event()
|
||||
self.stats_lock = threading.Lock()
|
||||
self.statuses = Counter()
|
||||
self.active = 0
|
||||
self.clients = set()
|
||||
self.started = time.monotonic()
|
||||
self.request_queue_size = config.request_queue
|
||||
super().__init__((config.app_host, config.app_port), Handler)
|
||||
self.threads = [threading.Thread(target=self.worker, name="http-" + str(n), daemon=True)
|
||||
for n in range(config.workers)]
|
||||
for thread in self.threads:
|
||||
thread.start()
|
||||
|
||||
def get_request(self):
|
||||
client, address = super().get_request()
|
||||
client.settimeout(self.config.socket_timeout)
|
||||
return client, address
|
||||
|
||||
def record(self, status):
|
||||
with self.stats_lock:
|
||||
self.statuses[str(status)] += 1
|
||||
|
||||
def process_request(self, request, address):
|
||||
try:
|
||||
if self.draining.is_set():
|
||||
raise queue.Full()
|
||||
self.jobs.put_nowait((request, address))
|
||||
except queue.Full:
|
||||
# Transport admission before HTTP parsing: bounded time, no extra thread.
|
||||
identifier = str(uuid.uuid4())
|
||||
body = json.dumps(error_body(503, "Request queue full or shutting down", identifier)).encode()
|
||||
headers = ("HTTP/1.1 503 Service Unavailable\r\nContent-Type: application/json\r\n"
|
||||
"Connection: close\r\nRetry-After: 1\r\nX-Request-Id: " + identifier +
|
||||
"\r\nX-Instance-Id: " + self.instance_id +
|
||||
"\r\nContent-Length: " + str(len(body)) + "\r\n\r\n").encode()
|
||||
try:
|
||||
request.settimeout(.05)
|
||||
# Wait for the first request bytes: closing before a local client
|
||||
# finishes sendall can otherwise discard the 503 with a TCP reset.
|
||||
try:
|
||||
request.recv(16384)
|
||||
except OSError:
|
||||
pass
|
||||
request.sendall(headers + body)
|
||||
request.shutdown(socket.SHUT_WR)
|
||||
request.settimeout(.01)
|
||||
for _ in range(5):
|
||||
if not request.recv(16384):
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
self.shutdown_request(request)
|
||||
self.record(503)
|
||||
log_event(event="queue_rejected", status=503, request_id=identifier)
|
||||
|
||||
def worker(self):
|
||||
while not self.draining.is_set() or not self.jobs.empty():
|
||||
try:
|
||||
request, address = self.jobs.get(timeout=.1)
|
||||
except queue.Empty:
|
||||
continue
|
||||
with self.stats_lock:
|
||||
self.active += 1
|
||||
self.clients.add(request)
|
||||
try:
|
||||
self.finish_request(request, address)
|
||||
except OSError:
|
||||
pass
|
||||
except Exception:
|
||||
log_event(event="worker_error")
|
||||
finally:
|
||||
self.shutdown_request(request)
|
||||
with self.stats_lock:
|
||||
self.active -= 1
|
||||
self.clients.discard(request)
|
||||
self.jobs.task_done()
|
||||
|
||||
def server_close(self):
|
||||
self.draining.set()
|
||||
super().server_close()
|
||||
# Stop listening, reject queued work, let accepted in-flight work COMMIT
|
||||
# and send its response before forcibly closing any remaining socket.
|
||||
deadline = time.monotonic() + 6
|
||||
for thread in self.threads:
|
||||
thread.join(timeout=max(0, deadline - time.monotonic()))
|
||||
with self.stats_lock:
|
||||
clients = list(self.clients)
|
||||
for client in clients:
|
||||
try:
|
||||
client.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
while True:
|
||||
try:
|
||||
request, _ = self.jobs.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
self.shutdown_request(request)
|
||||
self.jobs.task_done()
|
||||
self.store.close()
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
server_version = "Messenger"
|
||||
sys_version = ""
|
||||
|
||||
def setup(self):
|
||||
super().setup()
|
||||
self.request_id = str(uuid.uuid4())
|
||||
self.received = time.monotonic()
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
def parse_request(self):
|
||||
original = self.rfile
|
||||
|
||||
class HeaderBudget:
|
||||
remaining = 16384
|
||||
|
||||
def readline(self, limit=-1):
|
||||
line = original.readline(min(limit, self.remaining + 1) if limit >= 0 else self.remaining + 1)
|
||||
self.remaining -= len(line)
|
||||
if self.remaining < 0:
|
||||
raise http.client.LineTooLong("header section")
|
||||
return line
|
||||
|
||||
self.rfile = HeaderBudget()
|
||||
try:
|
||||
return super().parse_request()
|
||||
finally:
|
||||
self.rfile = original
|
||||
|
||||
def send_error(self, code, message=None, explain=None):
|
||||
self.reply(code if code in CODES else 400, error_body(
|
||||
code if code in CODES else 400, "Invalid HTTP request", self.request_id))
|
||||
|
||||
def reply(self, status, body):
|
||||
raw = b'' if status == 204 else json.dumps(body, ensure_ascii=False, allow_nan=False).encode('utf-8')
|
||||
content_type = 'application/json'
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("X-Request-Id", self.request_id)
|
||||
self.send_header("X-Instance-Id", self.server.instance_id)
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("Connection", "close")
|
||||
if status == 401:
|
||||
challenge = ('Basic realm="messenger", charset="UTF-8"'
|
||||
if urlsplit(self.path).path == '/api/v1/auth/sessions' else 'Bearer realm="messenger"')
|
||||
self.send_header('WWW-Authenticate', challenge)
|
||||
if status in (429, 503):
|
||||
self.send_header("Retry-After", "1")
|
||||
self.end_headers()
|
||||
self.close_connection = True
|
||||
self.wfile.write(raw)
|
||||
self.server.record(status)
|
||||
# No URL query, header, username, text, or exception detail in logs.
|
||||
log_event(event="request", method=self.command, status=status,
|
||||
request_id=self.request_id, elapsed_ms=round(1000 * (time.monotonic() - self.received), 3))
|
||||
|
||||
def handle_expect_100(self):
|
||||
# Do not acknowledge a large unauthorized request before checking identity.
|
||||
return True
|
||||
|
||||
def body(self):
|
||||
if self.headers.get_all("Transfer-Encoding"):
|
||||
raise APIError(400, "Transfer-Encoding is unsupported")
|
||||
sizes = self.headers.get_all("Content-Length", [])
|
||||
if len(sizes) != 1 or not sizes[0].isascii() or not sizes[0].isdigit() or len(sizes[0]) > 10:
|
||||
raise APIError(400, "One valid Content-Length is required")
|
||||
size = int(sizes[0])
|
||||
if size > self.server.config.max_body_bytes:
|
||||
raise APIError(413, "Request body exceeds byte limit")
|
||||
if self.headers.get_content_type() != "application/json":
|
||||
raise APIError(415, "Expected application/json")
|
||||
if self.headers.get("Expect", "").lower() == "100-continue":
|
||||
self.send_response_only(100)
|
||||
self.end_headers()
|
||||
raw = self.rfile.read(size)
|
||||
if len(raw) != size:
|
||||
raise APIError(400, "Incomplete request body")
|
||||
|
||||
def pairs(values):
|
||||
result = {}
|
||||
for key, value in values:
|
||||
if key in result:
|
||||
raise ValueError("duplicate key")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
def constant(_):
|
||||
raise ValueError("non JSON constant")
|
||||
|
||||
try:
|
||||
return json.loads(raw.decode("utf-8"), object_pairs_hook=pairs, parse_constant=constant)
|
||||
except (ValueError, UnicodeError, RecursionError):
|
||||
raise APIError(400, "Invalid JSON") from None
|
||||
|
||||
def dispatch(self):
|
||||
try:
|
||||
url = urlsplit(self.path)
|
||||
except ValueError:
|
||||
raise APIError(400, "Invalid request target") from None
|
||||
path, method = url.path, self.command
|
||||
store = self.server.store
|
||||
if self.server.draining.is_set():
|
||||
raise APIError(503, "Shutting down")
|
||||
if method == 'GET' and path == '/health/live':
|
||||
return 200, {'status': 'ok'}
|
||||
if method == 'GET' and path == '/health/ready':
|
||||
store.ready()
|
||||
return 200, {'status': 'ok'}
|
||||
if path == '/api/v1/users' and method == 'POST':
|
||||
return 201, store.create_user(self.body())
|
||||
headers = self.headers.get_all('Authorization', [])
|
||||
authorization = headers[0] if len(headers) == 1 else None
|
||||
if path == '/api/v1/auth/sessions' and method == 'POST':
|
||||
if self.headers.get('Transfer-Encoding') or self.headers.get('Content-Length', '0') != '0':
|
||||
raise APIError(400, 'Login takes no request body')
|
||||
return 201, store.login(authorization)
|
||||
actor, session_key = store.auth(authorization)
|
||||
if method == 'DELETE' and path == '/api/v1/auth/sessions/current':
|
||||
store.cache.delete(session_key)
|
||||
return 204, None
|
||||
if method == 'GET' and path == '/api/v1/users/me':
|
||||
return 200, store.me(actor)
|
||||
parts = path.strip("/").split("/")
|
||||
chat_id = None
|
||||
if len(parts) >= 4 and parts[:3] == ["api", "v1", "chats"]:
|
||||
chat_id = store.chat_access(actor, parts[3])
|
||||
if method == "POST" and path == "/api/v1/chats":
|
||||
return 201, store.create_chat(actor, self.body())
|
||||
if method == "POST" and chat_id and len(parts) == 5 and parts[4] == "messages":
|
||||
keys = self.headers.get_all('Idempotency-Key', [])
|
||||
key = keys[0] if len(keys) == 1 else None
|
||||
return 201, store.create_message(actor, chat_id, self.body(), key)
|
||||
if method == "GET":
|
||||
if chat_id and len(parts) == 4:
|
||||
return 200, store.chat(chat_id)
|
||||
if path == "/api/v1/chats" or (chat_id and len(parts) == 5 and parts[4] == "messages"):
|
||||
try:
|
||||
query = parse_qs(url.query, keep_blank_values=True, strict_parsing=True, max_num_fields=8)
|
||||
except ValueError:
|
||||
raise APIError(400, "Invalid query") from None
|
||||
return 200, store.page(actor, chat_id, query)
|
||||
raise APIError(404, "Object not found")
|
||||
|
||||
def handle_api(self):
|
||||
try:
|
||||
status, result = self.dispatch()
|
||||
except APIError as error:
|
||||
status = error.status
|
||||
result = error_body(status, error.message, self.request_id)
|
||||
except (psycopg.OperationalError, psycopg.InterfaceError, psycopg.errors.QueryCanceled,
|
||||
psycopg.errors.LockNotAvailable, PoolTimeout, TooManyRequests, redis.RedisError):
|
||||
status, result = 503, error_body(503, 'Dependency temporarily unavailable', self.request_id)
|
||||
except (TimeoutError, socket.timeout):
|
||||
status, result = 400, error_body(400, "Request read timeout", self.request_id)
|
||||
except Exception:
|
||||
status, result = 500, error_body(500, "Internal error", self.request_id)
|
||||
log_event(event="internal_error", request_id=self.request_id)
|
||||
try:
|
||||
self.reply(status, result)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = do_OPTIONS = handle_api
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
# Pool diagnostics may include connection details; application emits sanitized errors.
|
||||
logging.getLogger('psycopg.pool').disabled = True
|
||||
config = Config.from_env()
|
||||
server = Server(config)
|
||||
|
||||
def stop(signum, _):
|
||||
if not server.draining.is_set():
|
||||
server.draining.set()
|
||||
log_event(event="shutdown_started", signal=signum)
|
||||
threading.Thread(target=server.shutdown, daemon=True).start()
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
log_event(event="started", instance_id=server.instance_id, port=config.app_port, workers=config.workers)
|
||||
try:
|
||||
server.serve_forever(poll_interval=.1)
|
||||
finally:
|
||||
server.server_close()
|
||||
log_event(event="shutdown_complete")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user