[+] add project

This commit is contained in:
2026-11-10 23:47:45 +03:00
parent 65003b6119
commit 982fe0e6d2
19 changed files with 1398 additions and 25 deletions
View File
+689
View File
@@ -0,0 +1,689 @@
import base64
import binascii
import hashlib
import json
import logging
import os
import re
import secrets
import uuid
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
import psycopg
import redis
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
from fastapi import Depends, FastAPI, Header, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field, field_validator
from psycopg.errors import UniqueViolation
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool, PoolTimeout
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.settings import database_connection, session_ttl_seconds
logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"))
logger = logging.getLogger("messenger")
PASSWORD_HASHER = PasswordHasher()
USERNAME_PATTERN = re.compile(r"^[a-z0-9_]{3,32}$")
CURSOR_VERSION = 1
MAX_POOL_SIZE = int(os.environ.get("DB_POOL_MAX_SIZE", "10"))
if MAX_POOL_SIZE < 1 or MAX_POOL_SIZE > 50:
raise RuntimeError("DB_POOL_MAX_SIZE must be between 1 and 50")
class APIError(Exception):
def __init__(
self, status_code: int, code: str, message: str, challenge: Optional[str] = None
) -> None:
self.status_code = status_code
self.code = code
self.message = message
self.challenge = challenge
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
class UserInput(StrictModel):
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("display_name")
@classmethod
def display_name_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("display_name must not be blank")
return value
@field_validator("password")
@classmethod
def password_no_nul(cls, value: str) -> str:
if "\x00" in value:
raise ValueError("password contains an invalid character")
return value
class ChatInput(StrictModel):
title: str = Field(min_length=1, max_length=100)
member_ids: List[str] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def title_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("title must not be blank")
return value
class MessageInput(StrictModel):
text: str = Field(min_length=1, max_length=4000)
def utc_string(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace(
"+00:00", "Z"
)
def user_json(row: Dict[str, Any]) -> Dict[str, str]:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": utc_string(row["created_at"]),
}
def chat_json(row: Dict[str, Any], member_ids: List[str]) -> Dict[str, Any]:
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": member_ids,
"created_at": utc_string(row["created_at"]),
}
def message_json(row: Dict[str, Any]) -> Dict[str, str]:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": utc_string(row["created_at"]),
}
def db_unavailable() -> APIError:
return APIError(503, "unavailable", "Сервис временно недоступен")
def get_connection():
pool: ConnectionPool = app.state.pool
try:
with pool.connection(timeout=2) as connection:
yield connection
except (psycopg.OperationalError, PoolTimeout) as exc:
logger.warning("database connection unavailable: %s", type(exc).__name__)
raise db_unavailable() from None
@asynccontextmanager
async def lifespan(application: FastAPI):
session_ttl_seconds()
application.state.pool = ConnectionPool(
conninfo="",
kwargs={
**database_connection(),
"autocommit": True,
"row_factory": dict_row,
},
min_size=1,
max_size=MAX_POOL_SIZE,
timeout=2,
max_lifetime=1800,
open=True,
name="messenger-api",
)
redis_url = os.environ.get("REDIS_URL", "redis://localhost:6379/0")
application.state.redis = redis.Redis.from_url(
redis_url,
socket_connect_timeout=1,
socket_timeout=1,
decode_responses=True,
health_check_interval=30,
)
application.state.instance_id = str(uuid.uuid4())
try:
yield
finally:
application.state.redis.close()
application.state.pool.close()
app = FastAPI(title="Messenger API", version="1.0.0", lifespan=lifespan)
@app.middleware("http")
async def request_metadata(request: Request, call_next):
request_id = request.headers.get("X-Request-Id", "")
if not request_id or len(request_id) > 128:
request_id = str(uuid.uuid4())
request.state.request_id = request_id
try:
response = await call_next(request)
except Exception:
logger.exception("unhandled request failure")
response = JSONResponse(
status_code=500,
content={
"error": {
"code": "internal_error",
"message": "Внутренняя ошибка",
"request_id": request_id,
}
},
)
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = request.app.state.instance_id
return response
@app.exception_handler(APIError)
async def handle_api_error(request: Request, exc: APIError):
headers = {"WWW-Authenticate": exc.challenge} if exc.challenge else None
return JSONResponse(
status_code=exc.status_code,
content={
"error": {
"code": exc.code,
"message": exc.message,
"request_id": request.state.request_id,
}
},
headers=headers,
)
@app.exception_handler(RequestValidationError)
async def handle_validation_error(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=400,
content={
"error": {
"code": "invalid_request",
"message": "Некорректный запрос",
"request_id": request.state.request_id,
}
},
)
@app.exception_handler(StarletteHTTPException)
async def handle_http_error(request: Request, exc: StarletteHTTPException):
status = 404 if exc.status_code == 404 else exc.status_code
code = "not_found" if status == 404 else "invalid_request"
return JSONResponse(
status_code=status,
content={
"error": {
"code": code,
"message": "Объект не найден" if status == 404 else "Некорректный запрос",
"request_id": request.state.request_id,
}
},
)
@app.exception_handler(psycopg.Error)
async def handle_database_error(request: Request, exc: psycopg.Error):
logger.warning("database operation failed: %s", type(exc).__name__)
return JSONResponse(
status_code=503,
content={
"error": {
"code": "unavailable",
"message": "Сервис временно недоступен",
"request_id": request.state.request_id,
}
},
)
@app.exception_handler(PoolTimeout)
async def handle_pool_timeout(request: Request, exc: PoolTimeout):
return JSONResponse(
status_code=503,
content={
"error": {
"code": "unavailable",
"message": "Сервис временно недоступен",
"request_id": request.state.request_id,
}
},
)
def auth_error(challenge: str = 'Bearer realm="messenger"') -> APIError:
return APIError(401, "unauthorized", "Требуется действительная аутентификация", challenge)
def parse_uuid(value: str) -> uuid.UUID:
try:
return uuid.UUID(value)
except (ValueError, AttributeError, TypeError):
raise APIError(400, "invalid_request", "Некорректный UUID") from None
def authenticated_user(
request: Request,
authorization: Optional[str] = Header(default=None),
connection=Depends(get_connection),
) -> Dict[str, Any]:
if not authorization or not authorization.startswith("Bearer "):
raise auth_error()
token = authorization[7:]
if not token or len(token) > 256:
raise auth_error()
token_hash = hashlib.sha256(token.encode("utf-8")).digest()
now = datetime.now(timezone.utc)
cache = request.app.state.redis
cache_key = "session:" + token_hash.hex()
cached: Optional[Dict[str, Any]] = None
try:
raw = cache.get(cache_key)
if raw:
cached_value = json.loads(raw)
if isinstance(cached_value, dict):
cached = cached_value
else:
logger.warning("session cache entry has an invalid shape")
except (redis.RedisError, json.JSONDecodeError):
logger.warning("session cache read failed; using PostgreSQL")
try:
session = connection.execute(
"""
SELECT s.user_id, s.expires_at, s.revoked_at
FROM sessions AS s
WHERE s.token_hash = %s
""",
(token_hash,),
).fetchone()
except psycopg.Error as exc:
logger.warning("session lookup failed: %s", type(exc).__name__)
raise db_unavailable() from None
if not session or session["revoked_at"] is not None or session["expires_at"] <= now:
try:
cache.delete(cache_key)
except redis.RedisError:
logger.warning("expired session cache invalidation failed")
raise auth_error()
# PostgreSQL remains authoritative for expiry and revocation. Redis avoids
# a user-profile query on a cache hit.
if cached and cached.get("user_id") == str(session["user_id"]):
profile = cached.get("user")
if isinstance(profile, dict) and profile.get("id") == str(session["user_id"]):
user = profile
else:
cached = None
else:
cached = None
if not cached:
profile_row = connection.execute(
"""
SELECT id, username, display_name, created_at
FROM users WHERE id = %s
""",
(session["user_id"],),
).fetchone()
if not profile_row:
raise auth_error()
user = user_json(profile_row)
remaining = max(1, int((session["expires_at"] - now).total_seconds()))
try:
cache.set(
cache_key,
json.dumps({"user_id": str(session["user_id"]), "user": user}),
ex=remaining,
)
except redis.RedisError:
logger.warning("session cache write failed; continuing with PostgreSQL")
request.state.token_hash = token_hash
return user
@app.get("/health/live")
def live() -> Dict[str, str]:
return {"status": "ok"}
@app.get("/health/ready")
def ready(request: Request, connection=Depends(get_connection)) -> Dict[str, str]:
try:
connection.execute("SELECT 1")
request.app.state.redis.ping()
except (psycopg.Error, redis.RedisError):
raise db_unavailable() from None
return {"status": "ok"}
@app.post("/api/v1/users", status_code=201)
def register_user(payload: UserInput, connection=Depends(get_connection)):
user_id = uuid.uuid4()
password_hash = PASSWORD_HASHER.hash(payload.password)
try:
with connection.transaction():
row = connection.execute(
"""
INSERT INTO users (id, username, display_name, password_hash)
VALUES (%s, %s, %s, %s)
RETURNING id, username, display_name, created_at
""",
(user_id, payload.username, payload.display_name, password_hash),
).fetchone()
except UniqueViolation:
raise APIError(409, "conflict", "Имя пользователя уже занято") from None
except psycopg.Error as exc:
logger.warning("user registration failed: %s", type(exc).__name__)
raise db_unavailable() from None
return user_json(row)
def decode_basic_credentials(authorization: Optional[str]) -> Tuple[str, str]:
challenge = 'Basic realm="messenger", charset="UTF-8"'
if not authorization or not authorization.startswith("Basic "):
raise auth_error(challenge)
try:
raw = base64.b64decode(authorization[6:], validate=True).decode("utf-8")
username, password = raw.split(":", 1)
except (binascii.Error, UnicodeDecodeError, ValueError):
raise auth_error(challenge) from None
if not USERNAME_PATTERN.fullmatch(username) or not 12 <= len(password) <= 128:
raise auth_error(challenge)
return username, password
@app.post("/api/v1/auth/sessions", status_code=201)
def create_session(
request: Request,
authorization: Optional[str] = Header(default=None),
connection=Depends(get_connection),
):
username, password = decode_basic_credentials(authorization)
row = connection.execute(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users WHERE username = %s
""",
(username,),
).fetchone()
if not row:
raise auth_error('Basic realm="messenger", charset="UTF-8"')
try:
PASSWORD_HASHER.verify(row["password_hash"], password)
except (VerifyMismatchError, VerificationError, InvalidHashError):
raise auth_error('Basic realm="messenger", charset="UTF-8"') from None
token = secrets.token_urlsafe(32)
token_hash = hashlib.sha256(token.encode("utf-8")).digest()
expires_at = datetime.now(timezone.utc) + timedelta(seconds=session_ttl_seconds())
try:
with connection.transaction():
connection.execute(
"""
INSERT INTO sessions (token_hash, user_id, expires_at)
VALUES (%s, %s, %s)
""",
(token_hash, row["id"], expires_at),
)
except psycopg.Error as exc:
logger.warning("session creation failed: %s", type(exc).__name__)
raise db_unavailable() from None
user = user_json(row)
try:
request.app.state.redis.set(
"session:" + token_hash.hex(),
json.dumps({"user_id": str(row["id"]), "user": user}),
ex=session_ttl_seconds(),
)
except redis.RedisError:
logger.warning("session cache write failed; session remains durable in PostgreSQL")
return {
"token": token,
"token_type": "Bearer",
"expires_at": utc_string(expires_at),
"user": user,
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def revoke_session(
request: Request,
user: Dict[str, Any] = Depends(authenticated_user),
connection=Depends(get_connection),
):
token_hash: bytes = request.state.token_hash
try:
with connection.transaction():
result = connection.execute(
"""
UPDATE sessions SET revoked_at = clock_timestamp()
WHERE token_hash = %s AND revoked_at IS NULL
""",
(token_hash,),
)
if result.rowcount != 1:
raise auth_error()
except APIError:
raise
except psycopg.Error as exc:
logger.warning("session revocation failed: %s", type(exc).__name__)
raise db_unavailable() from None
try:
request.app.state.redis.delete("session:" + token_hash.hex())
except redis.RedisError:
logger.warning("revoked session cache invalidation failed")
return Response(status_code=204)
@app.get("/api/v1/users/me")
def current_user(user: Dict[str, Any] = Depends(authenticated_user)):
return user
def member_ids_for(connection, chat_id: uuid.UUID) -> List[str]:
rows = connection.execute(
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
(chat_id,),
).fetchall()
return [str(row["user_id"]) for row in rows]
def require_chat_member(
connection, chat_id: uuid.UUID, user_id: uuid.UUID
) -> Dict[str, Any]:
row = connection.execute(
"""
SELECT c.id, c.title, c.created_at
FROM chats AS c JOIN chat_members AS cm ON cm.chat_id = c.id
WHERE c.id = %s AND cm.user_id = %s
""",
(chat_id, user_id),
).fetchone()
if not row:
raise APIError(404, "not_found", "Объект не найден")
return row
@app.post("/api/v1/chats", status_code=201)
def create_chat(
payload: ChatInput,
user: Dict[str, Any] = Depends(authenticated_user),
connection=Depends(get_connection),
):
ids = [parse_uuid(member_id) for member_id in payload.member_ids]
if len(set(ids)) != len(ids) or uuid.UUID(user["id"]) not in ids:
raise APIError(400, "invalid_request", "Некорректный список участников")
chat_id = uuid.uuid4()
try:
with connection.transaction():
found = connection.execute(
"SELECT id FROM users WHERE id = ANY(%s)",
(ids,),
).fetchall()
if len(found) != len(ids):
raise APIError(400, "invalid_request", "Участник не существует")
chat = connection.execute(
"""
INSERT INTO chats (id, title) VALUES (%s, %s)
RETURNING id, title, created_at
""",
(chat_id, payload.title),
).fetchone()
for member_id in ids:
connection.execute(
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
(chat_id, member_id),
)
except APIError:
raise
except psycopg.Error as exc:
logger.warning("chat creation rolled back: %s", type(exc).__name__)
raise db_unavailable() from None
return chat_json(chat, [str(member_id) for member_id in sorted(ids)])
@app.get("/api/v1/chats")
def list_chats(
user: Dict[str, Any] = Depends(authenticated_user),
connection=Depends(get_connection),
limit: int = 50,
cursor: Optional[str] = None,
):
if limit < 1 or limit > 100:
raise APIError(400, "invalid_request", "limit должен быть от 1 до 100")
cursor_values = decode_cursor(cursor, "chats") if cursor else None
parameters: List[Any] = [uuid.UUID(user["id"])]
clause = ""
if cursor_values:
clause = "AND (c.created_at, c.id) > (%s, %s)"
parameters.extend(cursor_values)
parameters.append(limit + 1)
rows = connection.execute(
"""
SELECT c.id, c.title, c.created_at
FROM chats c JOIN chat_members cm ON cm.chat_id = c.id
WHERE cm.user_id = %s
"""
+ clause
+ " ORDER BY c.created_at, c.id LIMIT %s",
parameters,
).fetchall()
has_more = len(rows) > limit
rows = rows[:limit]
items = [
chat_json(row, member_ids_for(connection, row["id"]))
for row in rows
]
next_cursor = encode_cursor("chats", rows[-1]) if has_more and rows else None
return {"items": items, "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(
chat_id: str,
user: Dict[str, Any] = Depends(authenticated_user),
connection=Depends(get_connection),
):
parsed_id = parse_uuid(chat_id)
row = require_chat_member(connection, parsed_id, uuid.UUID(user["id"]))
return chat_json(row, member_ids_for(connection, parsed_id))
def encode_cursor(kind: str, row: Dict[str, Any]) -> str:
payload = json.dumps(
[CURSOR_VERSION, kind, str(row["created_at"]), str(row["id"])],
separators=(",", ":"),
).encode("utf-8")
return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
def decode_cursor(value: str, kind: str) -> Tuple[datetime, uuid.UUID]:
try:
padded = value + "=" * (-len(value) % 4)
decoded = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")))
if (
not isinstance(decoded, list)
or len(decoded) != 4
or decoded[0] != CURSOR_VERSION
or decoded[1] != kind
):
raise ValueError
created_at = datetime.fromisoformat(decoded[2])
if created_at.tzinfo is None:
raise ValueError
return created_at, uuid.UUID(decoded[3])
except (ValueError, TypeError, UnicodeError, json.JSONDecodeError):
raise APIError(400, "invalid_request", "Некорректный cursor") from None
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def create_message(
chat_id: str,
payload: MessageInput,
user: Dict[str, Any] = Depends(authenticated_user),
connection=Depends(get_connection),
):
parsed_chat_id = parse_uuid(chat_id)
chat = require_chat_member(connection, parsed_chat_id, uuid.UUID(user["id"]))
if not payload.text.strip():
raise APIError(400, "invalid_request", "Сообщение не может быть пустым")
row = connection.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES (%s, %s, %s, %s)
RETURNING id, chat_id, sender_id, text, created_at
""",
(uuid.uuid4(), chat["id"], uuid.UUID(user["id"]), payload.text),
).fetchone()
return message_json(row)
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(
chat_id: str,
user: Dict[str, Any] = Depends(authenticated_user),
connection=Depends(get_connection),
limit: int = 50,
cursor: Optional[str] = None,
):
if limit < 1 or limit > 100:
raise APIError(400, "invalid_request", "limit должен быть от 1 до 100")
parsed_chat_id = parse_uuid(chat_id)
chat = require_chat_member(connection, parsed_chat_id, uuid.UUID(user["id"]))
cursor_values = decode_cursor(cursor, str(parsed_chat_id)) if cursor else None
parameters: List[Any] = [chat["id"]]
clause = ""
if cursor_values:
clause = "AND (created_at, id) > (%s, %s)"
parameters.extend(cursor_values)
parameters.append(limit + 1)
rows = connection.execute(
"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages WHERE chat_id = %s
"""
+ clause
+ " ORDER BY created_at, id LIMIT %s",
parameters,
).fetchall()
has_more = len(rows) > limit
rows = rows[:limit]
items = [message_json(row) for row in rows]
next_cursor = encode_cursor(str(parsed_chat_id), rows[-1]) if has_more and rows else None
return {"items": items, "next_cursor": next_cursor}
+35
View File
@@ -0,0 +1,35 @@
from pathlib import Path
import psycopg
from app.settings import database_connection
def main() -> None:
migration_dir = Path(__file__).with_name("migrations")
with psycopg.connect(**database_connection(), autocommit=False) as connection:
connection.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version varchar(255) PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT clock_timestamp()
)
"""
)
for migration in sorted(migration_dir.glob("*.sql")):
already_applied = connection.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(migration.name,),
).fetchone()
if already_applied:
continue
connection.execute(migration.read_text(encoding="utf-8"))
connection.execute(
"INSERT INTO schema_migrations (version) VALUES (%s)",
(migration.name,),
)
connection.commit()
if __name__ == "__main__":
main()
+54
View File
@@ -0,0 +1,54 @@
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY,
username varchar(32) NOT NULL UNIQUE,
display_name varchar(100) NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_nonblank CHECK (length(btrim(display_name)) > 0)
);
CREATE TABLE IF NOT EXISTS chats (
id uuid PRIMARY KEY,
title varchar(100) NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT chats_title_nonblank CHECK (length(btrim(title)) > 0)
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX IF NOT EXISTS chat_members_by_user
ON chat_members (user_id, chat_id);
CREATE TABLE IF NOT EXISTS messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text varchar(4000) NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT messages_text_nonblank CHECK (length(btrim(text)) > 0)
);
CREATE INDEX IF NOT EXISTS messages_history_keyset
ON messages (chat_id, created_at, id);
CREATE TABLE IF NOT EXISTS sessions (
token_hash bytea PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX IF NOT EXISTS sessions_active_by_expiry
ON sessions (expires_at)
WHERE revoked_at IS NULL;
CREATE TABLE IF NOT EXISTS schema_migrations (
version varchar(255) PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
+54
View File
@@ -0,0 +1,54 @@
import os
from pathlib import Path
from typing import Dict, Optional
def read_setting(
name: str,
file_name: str,
default: Optional[str] = None,
default_file: Optional[str] = None,
) -> str:
configured_secret_path = os.environ.get(file_name)
secret_path = configured_secret_path or default_file
if secret_path and (configured_secret_path or Path(secret_path).is_file()):
try:
return Path(secret_path).read_text(encoding="utf-8").strip()
except OSError as exc:
raise RuntimeError("Unable to read configured secret file") from exc
value = os.environ.get(name, default)
if value is None:
if default_file:
raise RuntimeError(
"Required setting is missing: "
+ name
+ "; set "
+ file_name
+ " or mount the secret at "
+ default_file
)
raise RuntimeError("Required application setting is missing: " + name)
return value
def database_connection() -> Dict[str, object]:
return {
"host": os.environ.get("DB_HOST", "localhost"),
"port": int(os.environ.get("DB_PORT", "5432")),
"dbname": os.environ.get("DB_NAME", "messenger"),
"user": os.environ.get("DB_USER", "messenger"),
"password": read_setting(
"DB_PASSWORD",
"DB_PASSWORD_FILE",
default_file="/run/secrets/database_password",
),
"connect_timeout": int(os.environ.get("DB_CONNECT_TIMEOUT_SECONDS", "3")),
"options": "-c statement_timeout=5000 -c lock_timeout=3000",
}
def session_ttl_seconds() -> int:
value = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
if value < 1:
raise RuntimeError("SESSION_TTL_SECONDS must be at least 1")
return value