This commit is contained in:
Бахрам
2026-10-29 17:16:55 +03:00
parent 65003b6119
commit c401ece9b1
30 changed files with 1459 additions and 18 deletions
View File
+14
View File
@@ -0,0 +1,14 @@
"""Runtime configuration; secret values are read only from mounted files."""
import os
from pathlib import Path
APP_HOST = os.getenv('APP_HOST', '0.0.0.0')
APP_PORT = int(os.getenv('APP_PORT', '8080'))
SESSION_TTL_SECONDS = int(os.getenv('SESSION_TTL_SECONDS', '3600'))
POOL_SIZE = int(os.getenv('DB_POOL_SIZE', '8'))
if SESSION_TTL_SECONDS < 1 or not 1 <= POOL_SIZE <= 32:
raise ValueError('Invalid TTL or pool size')
def secret(name):
return Path(os.environ[name + '_FILE']).read_text().strip()
+45
View File
@@ -0,0 +1,45 @@
class APIError(Exception):
def __init__(self, code: str, message: str, status_code: int = 400):
super().__init__(message)
self.code = code
self.message = message
self.status_code = status_code
def to_dict(self, request_id: str) -> dict:
return {
"error": {
"code": self.code,
"message": self.message,
"request_id": request_id,
}
}
class BadRequestError(APIError):
def __init__(self, message: str = "Invalid request"):
super().__init__(code="invalid_request", message=message, status_code=400)
class UnauthorizedError(APIError):
def __init__(self, message: str = "Unauthorized"):
super().__init__(code="unauthorized", message=message, status_code=401)
class NotFoundError(APIError):
def __init__(self, message: str = "Object not found"):
super().__init__(code="not_found", message=message, status_code=404)
class ConflictError(APIError):
def __init__(self, message: str = "Conflict"):
super().__init__(code="conflict", message=message, status_code=409)
class UnavailableError(APIError):
def __init__(self, message: str = "Service unavailable"):
super().__init__(code="unavailable", message=message, status_code=503)
class InternalError(APIError):
def __init__(self, message: str = "Internal server error"):
super().__init__(code="internal_error", message=message, status_code=500)
+53
View File
@@ -0,0 +1,53 @@
import logging
import signal
import sys
import threading
from pathlib import Path
# Ensure root directory is in sys.path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.config import APP_HOST, APP_PORT
from app.server import MessengerServer
from app.migrate import migrate
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
stream=sys.stdout,
)
logger = logging.getLogger("messenger")
def main():
migrate()
server = MessengerServer((APP_HOST, APP_PORT))
logger.info("Starting MTUSI Messenger server on %s:%d", APP_HOST, APP_PORT)
def handle_signal(sig_num, frame):
sig_name = signal.Signals(sig_num).name
logger.info("Received %s, initiating graceful shutdown...", sig_name)
server.is_shutting_down = True
def shutdown_thread():
server.shutdown()
server.server_close()
logger.info("Server stopped cleanly.")
threading.Thread(target=shutdown_thread, daemon=True).start()
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
try:
server.serve_forever()
except (KeyboardInterrupt, SystemExit):
logger.info("Server exiting...")
finally:
server.server_close()
server.storage.close()
logger.info("Shutdown completed.")
if __name__ == "__main__":
main()
+28
View File
@@ -0,0 +1,28 @@
"""Transactional, versioned SQL migrations protected by a database advisory lock."""
import hashlib
from pathlib import Path
import psycopg
from app.config import secret
def migrate():
with psycopg.connect(secret('DATABASE_URL'), connect_timeout=3) as conn:
conn.execute('SELECT pg_advisory_xact_lock(202602)')
conn.execute('''CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY, checksum text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT clock_timestamp())''')
for path in sorted((Path(__file__).resolve().parents[1] / 'migrations').glob('*.sql')):
sql = path.read_text()
checksum = hashlib.sha256(sql.encode()).hexdigest()
row = conn.execute('SELECT checksum FROM schema_migrations WHERE version=%s', (path.name,)).fetchone()
if row:
if row[0] != checksum:
raise RuntimeError('Applied migration has changed: ' + path.name)
continue
conn.execute(sql)
conn.execute('INSERT INTO schema_migrations(version, checksum) VALUES (%s,%s)', (path.name, checksum))
print('Applied migration ' + path.name, flush=True)
if __name__ == '__main__':
migrate()
+171
View File
@@ -0,0 +1,171 @@
import base64
import datetime as dt
import json
import re
import uuid
from typing import Any, Dict, List, Optional, Tuple
from app.errors import APIError, BadRequestError
USERNAME_REGEX = re.compile(r'^[a-z0-9_]{3,32}$')
def now_utc_z() -> str:
"""Return current server time in RFC 3339 UTC format ending with Z."""
return dt.datetime.now(dt.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
def parse_rfc3339(value: str) -> dt.datetime:
"""Parse RFC 3339 UTC timestamp ending with Z."""
if not isinstance(value, str) or not value.endswith('Z'):
raise ValueError("Timestamp must be UTC ending with Z")
return dt.datetime.fromisoformat(value[:-1] + '+00:00')
def validate_uuid(value: Any, field_name: str = "id") -> str:
if not isinstance(value, str):
raise BadRequestError(f"{field_name} must be a string")
try:
parsed = uuid.UUID(value)
except (ValueError, TypeError, AttributeError):
raise BadRequestError(f"{field_name} must be a valid UUID")
return str(parsed)
def validate_create_user(body: Any) -> Dict[str, Any]:
if not isinstance(body, dict):
raise BadRequestError("Request body must be a JSON object")
allowed_fields = {'username', 'display_name', 'password'}
if set(body.keys()) != allowed_fields:
extra = set(body.keys()) - allowed_fields
missing = allowed_fields - set(body.keys())
if missing:
raise BadRequestError(f"Missing required fields: {', '.join(missing)}")
if extra:
raise BadRequestError(f"Unexpected fields: {', '.join(extra)}")
username = body.get('username')
display_name = body.get('display_name')
if not isinstance(username, str) or not USERNAME_REGEX.fullmatch(username):
raise BadRequestError("username must match ^[a-z0-9_]{3,32}$")
if not isinstance(display_name, str):
raise BadRequestError("display_name must be a string")
if len(display_name) < 1 or len(display_name) > 100:
raise BadRequestError("display_name length must be between 1 and 100 characters")
if not display_name.strip():
raise BadRequestError("display_name cannot consist only of whitespace")
password = body['password']
if not isinstance(password, str) or not 12 <= len(password) <= 128 or not password.strip():
raise BadRequestError('password must contain 12–128 nonblank characters')
return {'username': username, 'display_name': display_name, 'password': password}
def validate_create_chat(body: Any) -> Dict[str, Any]:
if not isinstance(body, dict):
raise BadRequestError("Request body must be a JSON object")
allowed_fields = {'title', 'member_ids'}
if set(body.keys()) != allowed_fields:
extra = set(body.keys()) - allowed_fields
missing = allowed_fields - set(body.keys())
if missing:
raise BadRequestError(f"Missing required fields: {', '.join(missing)}")
if extra:
raise BadRequestError(f"Unexpected fields: {', '.join(extra)}")
title = body.get('title')
member_ids = body.get('member_ids')
if not isinstance(title, str):
raise BadRequestError("title must be a string")
if len(title) < 1 or len(title) > 100:
raise BadRequestError("title length must be between 1 and 100 characters")
if not title.strip():
raise BadRequestError("title cannot consist only of whitespace")
if not isinstance(member_ids, list):
raise BadRequestError("member_ids must be an array")
if len(member_ids) < 1 or len(member_ids) > 100:
raise BadRequestError("member_ids length must be between 1 and 100")
seen = set()
cleaned_members = []
for mid in member_ids:
mid_str = validate_uuid(mid, "member_ids element")
if mid_str in seen:
raise BadRequestError(f"Duplicate member_id: {mid_str}")
seen.add(mid_str)
cleaned_members.append(mid_str)
return {'title': title, 'member_ids': cleaned_members}
def validate_create_message(body: Any) -> Dict[str, Any]:
if not isinstance(body, dict):
raise BadRequestError("Request body must be a JSON object")
allowed_fields = {'text'}
if set(body.keys()) != allowed_fields:
extra = set(body.keys()) - allowed_fields
missing = allowed_fields - set(body.keys())
if missing:
raise BadRequestError(f"Missing required fields: {', '.join(missing)}")
if extra:
raise BadRequestError(f"Unexpected fields: {', '.join(extra)}")
text = body.get('text')
if not isinstance(text, str):
raise BadRequestError("text must be a string")
if len(text) < 1 or len(text) > 4000:
raise BadRequestError("text length must be between 1 and 4000 characters")
if not text.strip():
raise BadRequestError("text cannot consist only of whitespace")
return {'text': text}
def parse_limit(limit_param: Optional[str]) -> int:
if limit_param is None:
return 50
try:
limit = int(limit_param)
except (ValueError, TypeError):
raise BadRequestError("limit must be an integer")
if limit < 1 or limit > 100:
raise BadRequestError("limit must be between 1 and 100")
return limit
def encode_cursor(created_at: str, item_id: str, resource_type: str, chat_id: Optional[str] = None) -> str:
data = {
't': created_at,
'id': item_id,
'type': resource_type,
}
if chat_id is not None:
data['cid'] = chat_id
raw = json.dumps(data, separators=(',', ':')).encode('utf-8')
return base64.urlsafe_b64encode(raw).decode('ascii')
def decode_cursor(cursor_str: str, expected_type: str, expected_chat_id: Optional[str] = None) -> Tuple[dt.datetime, int]:
try:
if len(cursor_str) > 2048:
raise ValueError
raw = base64.b64decode(cursor_str.encode('ascii'), altchars=b'-_', validate=True)
data = json.loads(raw.decode('utf-8'))
if not isinstance(data, dict):
raise ValueError
if data.get('type') != expected_type:
raise BadRequestError("Cursor does not match resource type")
if expected_chat_id is not None and data.get('cid') != expected_chat_id:
raise BadRequestError("Cursor belongs to another chat")
t = parse_rfc3339(data['t'])
if t.utcoffset() != dt.timedelta(0):
raise ValueError
u_int = uuid.UUID(data['id']).int
return t, u_int
except APIError:
raise
except Exception:
raise BadRequestError("Invalid cursor format")
+300
View File
@@ -0,0 +1,300 @@
import base64
import binascii
import json
import socket
import psycopg
from psycopg_pool import PoolTimeout, TooManyRequests
import logging
import re
import time
import urllib.parse
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Dict, Optional, Tuple
from app.errors import (
APIError,
BadRequestError,
InternalError,
NotFoundError,
UnauthorizedError,
UnavailableError,
)
from app.models import (
parse_limit,
validate_create_chat,
validate_create_message,
validate_create_user,
validate_uuid,
)
from app.storage import PostgresStorage
logger = logging.getLogger("messenger")
CHAT_MESSAGES_PATTERN = re.compile(r"^/api/v1/chats/([^/]+)/messages$")
CHAT_DETAIL_PATTERN = re.compile(r"^/api/v1/chats/([^/]+)$")
class MessengerHandler(BaseHTTPRequestHandler):
server_version = "MTUSI-Messenger/1.0"
@property
def storage(self) -> PostgresStorage:
return self.server.storage # type: ignore
@property
def is_shutting_down(self) -> bool:
return getattr(self.server, "is_shutting_down", False)
def log_message(self, format: str, *args: Any):
# Suppress default BaseHTTPRequestHandler noisy log
pass
def _get_request_id(self) -> str:
return str(uuid.uuid4())
def setup(self):
super().setup()
self.connection.settimeout(10)
def _send_json(self, status_code: int, data: Optional[Dict[str, Any]], request_id: str):
body = b""
if data is not None and status_code != 204:
body = json.dumps(data, ensure_ascii=False).encode("utf-8")
self.send_response(status_code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.send_header("X-Request-Id", request_id)
if status_code == 401:
challenge = ('Basic realm="messenger", charset="UTF-8"' if
urllib.parse.urlparse(self.path).path == '/api/v1/auth/sessions'
else 'Bearer realm="messenger"')
self.send_header('WWW-Authenticate', challenge)
self.end_headers()
if body:
self.wfile.write(body)
def _send_error(self, err: APIError, request_id: str):
payload = err.to_dict(request_id)
self._send_json(err.status_code, payload, request_id)
def _read_json_body(self) -> Any:
if self.headers.get('Transfer-Encoding'):
raise BadRequestError('Transfer-Encoding is not supported')
if self.headers.get_content_type() != 'application/json':
raise APIError('unsupported_media_type', 'Expected application/json', 415)
content_length_header = self.headers.get("Content-Length")
if not content_length_header:
raise BadRequestError("Missing request body")
try:
content_length = int(content_length_header)
except (ValueError, TypeError):
raise BadRequestError("Invalid Content-Length header")
if content_length < 0 or content_length > 10 * 1024 * 1024:
raise BadRequestError("Payload size invalid")
raw_data = self.rfile.read(content_length)
if not raw_data:
raise BadRequestError("Empty request body")
try:
body = json.loads(raw_data.decode("utf-8"))
# Reject unpaired surrogates before a driver/KDF tries to encode them.
json.dumps(body, ensure_ascii=False).encode('utf-8')
return body
except (ValueError, UnicodeError):
raise BadRequestError("Malformed JSON in request body")
def _bearer(self):
parts = self.headers.get('Authorization', '').split()
if len(parts) != 2 or parts[0].lower() != 'bearer' or len(parts[1]) > 512:
raise UnauthorizedError()
return parts[1]
def _authenticate_user(self):
return self.storage.authenticate(self._bearer())
def _login(self):
parts = self.headers.get('Authorization', '').split()
if len(parts) != 2 or parts[0].lower() != 'basic' or len(parts[1]) > 2048:
raise UnauthorizedError('Invalid credentials')
try:
credential = base64.b64decode(parts[1], validate=True).decode('utf-8')
username, password = credential.split(':', 1)
if not re.fullmatch(r'[a-z0-9_]{3,32}', username) or not 12 <= len(password) <= 128:
raise ValueError
except (ValueError, UnicodeError, binascii.Error):
raise UnauthorizedError('Invalid credentials') from None
if self.headers.get('Transfer-Encoding') or self.headers.get('Content-Length', '0') != '0':
raise BadRequestError('Session creation has no body')
return self.storage.login(username, password)
def do_PUT(self):
self._handle_request("PUT")
def do_PATCH(self):
self._handle_request("PATCH")
def do_OPTIONS(self):
self._handle_request("OPTIONS")
def do_DELETE(self):
self._handle_request("DELETE")
def do_GET(self):
self._handle_request("GET")
def do_POST(self):
self._handle_request("POST")
def _handle_request(self, method: str):
start_time = time.monotonic()
request_id = self._get_request_id()
parsed_url = urllib.parse.urlparse(self.path)
path = parsed_url.path
query = urllib.parse.parse_qs(parsed_url.query, keep_blank_values=True)
status_code = 200
try:
if self.is_shutting_down and not path.startswith("/health/"):
raise UnavailableError("Server is shutting down")
# Route dispatcher
if method == "GET" and path == "/health/live":
self._send_json(200, {"status": "ok"}, request_id)
status_code = 200
elif method == "GET" and path == "/health/ready":
if self.is_shutting_down:
raise UnavailableError("Server is shutting down")
self.storage.ready()
self._send_json(200, {"status": "ok"}, request_id)
status_code = 200
elif method == "POST" and path == "/api/v1/users":
body = self._read_json_body()
validated = validate_create_user(body)
user = self.storage.create_user(**validated)
self._send_json(201, user, request_id)
status_code = 201
elif method == 'POST' and path == '/api/v1/auth/sessions':
self._send_json(201, self._login(), request_id)
status_code = 201
elif method == 'DELETE' and path == '/api/v1/auth/sessions/current':
self.storage.logout(self._bearer())
self._send_json(204, None, request_id)
status_code = 204
elif method == "GET" and path == "/api/v1/users/me":
actor = self._authenticate_user()
self._send_json(200, actor, request_id)
status_code = 200
elif method == "POST" and path == "/api/v1/chats":
actor = self._authenticate_user()
body = self._read_json_body()
validated = validate_create_chat(body)
chat = self.storage.create_chat(
creator_id=actor["id"],
title=validated["title"],
member_ids=validated["member_ids"],
)
self._send_json(201, chat, request_id)
status_code = 201
elif method == "GET" and path == "/api/v1/chats":
actor = self._authenticate_user()
limit_val = query.get("limit", [None])[0]
cursor_val = query.get("cursor", [None])[0]
limit = parse_limit(limit_val)
result = self.storage.list_chats(actor["id"], limit=limit, cursor=cursor_val)
self._send_json(200, result, request_id)
status_code = 200
else:
# Check regex routes
match_messages = CHAT_MESSAGES_PATTERN.match(path)
match_chat = CHAT_DETAIL_PATTERN.match(path)
if match_messages:
raw_chat_id = match_messages.group(1)
actor = self._authenticate_user()
chat_id = validate_uuid(raw_chat_id, "chat_id")
if method == "POST":
body = self._read_json_body()
validated = validate_create_message(body)
msg = self.storage.create_message(
chat_id=chat_id,
sender_id=actor["id"],
text=validated["text"],
)
self._send_json(201, msg, request_id)
status_code = 201
elif method == "GET":
limit_val = query.get("limit", [None])[0]
cursor_val = query.get("cursor", [None])[0]
limit = parse_limit(limit_val)
result = self.storage.list_messages(
user_id=actor["id"],
chat_id=chat_id,
limit=limit,
cursor=cursor_val,
)
self._send_json(200, result, request_id)
status_code = 200
else:
raise NotFoundError("Endpoint not found")
elif match_chat:
raw_chat_id = match_chat.group(1)
actor = self._authenticate_user()
chat_id = validate_uuid(raw_chat_id, "chat_id")
if method == "GET":
chat = self.storage.get_chat(user_id=actor["id"], chat_id=chat_id)
self._send_json(200, chat, request_id)
status_code = 200
else:
raise NotFoundError("Endpoint not found")
else:
raise NotFoundError(f"Route not found: {method} {path}")
except APIError as err:
status_code = err.status_code
self._send_error(err, request_id)
except (psycopg.OperationalError, psycopg.InterfaceError, psycopg.errors.QueryCanceled,
psycopg.errors.LockNotAvailable, PoolTimeout, TooManyRequests):
status_code = 503
self._send_error(UnavailableError(), request_id)
except (socket.timeout, ConnectionError):
status_code = 408
self.close_connection = True
except Exception as exc:
status_code = 500
logger.error("Unhandled exception type: %s", type(exc).__name__)
self._send_error(InternalError("Internal server error"), request_id)
finally:
elapsed_ms = (time.monotonic() - start_time) * 1000
# Safe structured log without payload content
logger.info(
"%s %s %d %.2fms req_id=%s",
method,
path,
status_code,
elapsed_ms,
request_id,
)
class MessengerServer(ThreadingHTTPServer):
daemon_threads = True
def __init__(self, server_address: Tuple[str, int], storage: Optional[PostgresStorage] = None):
super().__init__(server_address, MessengerHandler)
self.storage = storage or PostgresStorage()
self.is_shutting_down = False
+172
View File
@@ -0,0 +1,172 @@
"""Persistent users, chats, messages and sessions in PostgreSQL."""
import datetime as dt
import hashlib
import secrets
import uuid
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
from app.config import secret, POOL_SIZE, SESSION_TTL_SECONDS
from app.errors import BadRequestError, ConflictError, NotFoundError, UnauthorizedError
from app.models import decode_cursor, encode_cursor
def public(row):
return {key: (str(value) if isinstance(value, uuid.UUID) else
value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
if isinstance(value, dt.datetime) else value)
for key, value in row.items() if key != 'password_hash'}
def token_hash(token):
return hashlib.sha256(token.encode()).hexdigest()
class PostgresStorage:
def __init__(self):
self.pool = ConnectionPool(
secret('DATABASE_URL'), min_size=1, max_size=POOL_SIZE, timeout=2,
max_waiting=32, reconnect_timeout=3,
kwargs={'connect_timeout': 2, 'row_factory': dict_row,
'options': '-c statement_timeout=2500 -c lock_timeout=1500 -c timezone=UTC'},
check=ConnectionPool.check_connection,
)
self.pool.wait(timeout=15)
self.hasher = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=2)
self.dummy_hash = self.hasher.hash(secrets.token_urlsafe(32))
def close(self):
self.pool.close()
def ready(self):
with self.pool.connection() as conn:
conn.execute('SELECT 1')
def create_user(self, username, display_name, password):
password_hash = self.hasher.hash(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 id, username, display_name, created_at''',
(uuid.uuid4(), username, display_name, password_hash)).fetchone()
return public(row)
except psycopg.errors.UniqueViolation:
raise ConflictError('Username is already taken') from None
def get_user(self, user_id):
with self.pool.connection() as conn:
row = conn.execute('SELECT id,username,display_name,created_at FROM users WHERE id=%s', (user_id,)).fetchone()
return public(row) if row else None
def login(self, username, password):
with self.pool.connection() as conn:
row = conn.execute('SELECT * FROM users WHERE username=%s', (username,)).fetchone()
try:
self.hasher.verify(row['password_hash'] if row else self.dummy_hash, password)
except (VerifyMismatchError, VerificationError, InvalidHashError):
raise UnauthorizedError('Invalid credentials') from None
if not row:
raise UnauthorizedError('Invalid credentials')
token = secrets.token_urlsafe(32) # 256 random bits; never persist/log the raw token.
with self.pool.connection() as conn:
session = conn.execute('''INSERT INTO sessions(token_hash,user_id,expires_at)
VALUES (%s,%s,clock_timestamp() + %s * interval '1 second') RETURNING expires_at''',
(token_hash(token), row['id'], SESSION_TTL_SECONDS)).fetchone()
return {'token': token, 'token_type': 'Bearer',
'expires_at': public(session)['expires_at'], 'user': public(row)}
def authenticate(self, token):
# Check expiry against the database clock on every protected request.
with self.pool.connection() as conn:
row = conn.execute('''SELECT user_id FROM sessions
WHERE token_hash=%s AND expires_at > clock_timestamp()''', (token_hash(token),)).fetchone()
if not row:
raise UnauthorizedError()
user = self.get_user(row['user_id'])
if not user:
raise UnauthorizedError()
return user
def logout(self, token):
with self.pool.connection() as conn:
row = conn.execute('''DELETE FROM sessions WHERE token_hash=%s
AND expires_at > clock_timestamp() RETURNING user_id''', (token_hash(token),)).fetchone()
if not row:
raise UnauthorizedError()
@staticmethod
def _chat(conn, chat_id):
row = conn.execute('SELECT * FROM chats WHERE id=%s', (chat_id,)).fetchone()
result = public(row)
result['member_ids'] = [str(r['user_id']) for r in conn.execute(
'SELECT user_id FROM memberships WHERE chat_id=%s ORDER BY user_id', (chat_id,))]
return result
@staticmethod
def _access(conn, user_id, chat_id):
if not conn.execute('SELECT 1 FROM memberships WHERE chat_id=%s AND user_id=%s',
(chat_id, user_id)).fetchone():
raise NotFoundError('Chat not found')
def create_chat(self, creator_id, title, member_ids):
if creator_id not in member_ids:
raise BadRequestError('Creator must be included in member_ids')
try:
with self.pool.connection() as conn:
chat_id = uuid.uuid4()
conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (chat_id, title))
with conn.cursor() as cur:
cur.executemany('INSERT INTO memberships(chat_id,user_id) VALUES (%s,%s)',
[(chat_id, user_id) for user_id in member_ids])
chat = self._chat(conn, chat_id)
return chat
except psycopg.errors.ForeignKeyViolation:
# Exiting connection() rolls back chat and every already inserted member.
raise BadRequestError('Unknown participant') from None
def get_chat(self, user_id, chat_id):
with self.pool.connection() as conn:
self._access(conn, user_id, chat_id)
return self._chat(conn, chat_id)
def list_chats(self, user_id, limit=50, cursor=None):
params = [user_id]
condition = ''
if cursor is not None:
stamp, item_id = decode_cursor(cursor, 'chat', user_id)
condition = ' AND (c.created_at,c.id) > (%s,%s)'
params.extend([stamp, uuid.UUID(int=item_id)])
params.append(limit + 1)
with self.pool.connection() as conn:
rows = conn.execute('''SELECT c.* FROM chats c JOIN memberships m ON m.chat_id=c.id
WHERE m.user_id=%s''' + condition + ' ORDER BY c.created_at,c.id LIMIT %s', params).fetchall()
items = [self._chat(conn, row['id']) for row in rows[:limit]]
next_cursor = encode_cursor(items[-1]['created_at'], items[-1]['id'], 'chat', user_id) if len(rows) > limit else None
return {'items': items, 'next_cursor': next_cursor}
def create_message(self, chat_id, sender_id, text):
with self.pool.connection() as conn:
self._access(conn, sender_id, chat_id)
row = conn.execute('''INSERT INTO messages(id,chat_id,sender_id,text)
VALUES (%s,%s,%s,%s) RETURNING *''', (uuid.uuid4(), chat_id, sender_id, text)).fetchone()
return public(row)
def list_messages(self, user_id, chat_id, limit=50, cursor=None):
params = [chat_id]
condition = ''
if cursor is not None:
stamp, item_id = decode_cursor(cursor, 'message', chat_id)
condition = ' AND (created_at,id) > (%s,%s)'
params.extend([stamp, uuid.UUID(int=item_id)])
params.append(limit + 1)
with self.pool.connection() as conn:
self._access(conn, user_id, chat_id)
rows = conn.execute('SELECT * FROM messages WHERE chat_id=%s' + condition +
' ORDER BY created_at,id LIMIT %s', params).fetchall()
items = [public(row) for row in rows[:limit]]
next_cursor = encode_cursor(items[-1]['created_at'], items[-1]['id'], 'message', chat_id) if len(rows) > limit else None
return {'items': items, 'next_cursor': next_cursor}