level 4, changed to HAProxy

This commit is contained in:
2026-11-07 18:18:43 +03:00
parent 124c83e450
commit eb4e00e412
33 changed files with 3932 additions and 231 deletions
+32 -1
View File
@@ -1,17 +1,48 @@
import logging
import threading
import uvicorn
from .config import load_settings
from .drain import draining
logger = logging.getLogger('messenger')
class DrainingServer(uvicorn.Server):
"""First SIGTERM/SIGINT: keep serving for drain_seconds with readiness 503, then uvicorn's graceful stop.
drain_seconds must exceed the LB detection time (HAProxy inter 1s x fall 2 + timeout check 1s),
so the replica is out of rotation before it stops accepting connections.
"""
def __init__(self, config: uvicorn.Config, drain_seconds: float):
super().__init__(config)
self.drain_seconds = drain_seconds
def handle_exit(self, sig, frame) -> None:
if draining.is_set() or self.drain_seconds <= 0:
draining.set()
super().handle_exit(sig, frame)
return
draining.set()
logger.warning('signal %s: draining for %.1f s before shutdown', sig, self.drain_seconds)
timer = threading.Timer(self.drain_seconds, super().handle_exit, (sig, frame))
timer.daemon = True
timer.start()
def main() -> None:
settings = load_settings()
uvicorn.run(
config = uvicorn.Config(
'app.main:app',
host=settings.host,
port=settings.port,
log_level=settings.log_level,
timeout_graceful_shutdown=settings.shutdown_timeout,
timeout_keep_alive=settings.keepalive_timeout,
)
DrainingServer(config, settings.drain_seconds).run()
if __name__ == '__main__':
+44 -15
View File
@@ -2,6 +2,7 @@ import os
import socket
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import quote
@dataclass(frozen=True)
@@ -11,39 +12,67 @@ class Settings:
env: str
log_level: str
shutdown_timeout: int
drain_seconds: float
keepalive_timeout: int
session_ttl_seconds: int
idempotency_ttl_seconds: int
database_url: str
instance_id: str
app_version: str
def _secret(file_var: str, value_var: str) -> str:
"""A *_FILE variable wins. The secret value is not logged."""
file_name = os.getenv(file_var, '').strip()
if file_name:
try:
value = Path(file_name).read_text(encoding='utf-8').strip()
except OSError:
raise RuntimeError('%s could not be read' % file_var) from None
if not value:
raise RuntimeError('%s is empty' % file_var)
return value
value = os.getenv(value_var, '').strip()
def _read_secret_file(file_var: str, file_name: str) -> str:
try:
value = Path(file_name).read_text(encoding='utf-8').strip()
except OSError:
raise RuntimeError('%s could not be read' % file_var) from None
if not value:
raise RuntimeError('%s or %s is required' % (value_var, file_var))
raise RuntimeError('%s is empty' % file_var)
return value
def _database_url() -> str:
"""DATABASE_URL_FILE, then DATABASE_URL, then DB_* parts with the password from DB_PASSWORD_FILE.
Secret values are never logged.
"""
file_name = os.getenv('DATABASE_URL_FILE', '').strip()
if file_name:
return _read_secret_file('DATABASE_URL_FILE', file_name)
value = os.getenv('DATABASE_URL', '').strip()
if value:
return value
password_file = os.getenv('DB_PASSWORD_FILE', '').strip()
if not password_file:
raise RuntimeError('DATABASE_URL, DATABASE_URL_FILE or DB_PASSWORD_FILE is required')
password = _read_secret_file('DB_PASSWORD_FILE', password_file)
parts = {name: os.getenv(name, '').strip() for name in ('DB_HOST', 'DB_USER', 'DB_NAME')}
missing = [name for name, part in parts.items() if not part]
if missing:
raise RuntimeError('%s required with DB_PASSWORD_FILE' % ', '.join(missing))
return 'postgresql://%s:%s@%s:%s/%s' % (
quote(parts['DB_USER'], safe=''),
quote(password, safe=''),
parts['DB_HOST'],
int(os.getenv('DB_PORT', '5432')),
quote(parts['DB_NAME'], safe=''),
)
def load_settings() -> Settings:
return Settings(
host=os.getenv('APP_HOST', '0.0.0.0'),
port=int(os.getenv('APP_PORT', '8080')),
env=os.getenv('APP_ENV', 'lab'),
log_level=os.getenv('LOG_LEVEL', 'info').lower(),
shutdown_timeout=int(os.getenv('SHUTDOWN_TIMEOUT_SECONDS', '5')),
shutdown_timeout=int(os.getenv('SHUTDOWN_TIMEOUT_SECONDS', '3')),
drain_seconds=float(os.getenv('DRAIN_SECONDS', '4')),
# Longer than HAProxy's idle-connection purge (pool-purge-delay 5 s), so the LB usually closes them first.
keepalive_timeout=int(os.getenv('KEEPALIVE_TIMEOUT_SECONDS', '10')),
session_ttl_seconds=int(os.getenv('SESSION_TTL_SECONDS', '3600')),
idempotency_ttl_seconds=int(os.getenv('IDEMPOTENCY_TTL_SECONDS', '86400')),
database_url=_secret('DATABASE_URL_FILE', 'DATABASE_URL'),
database_url=_database_url(),
# Docker sets the hostname to the short container ID, which stop-one.sh maps back to a container.
instance_id=os.getenv('INSTANCE_ID', '').strip() or socket.gethostname(),
app_version=os.getenv('APP_VERSION', 'dev').strip() or 'dev',
)
+4
View File
@@ -0,0 +1,4 @@
"""Set on SIGTERM: readiness turns 503 so the LB stops routing here while requests are still served."""
import threading
draining = threading.Event()
+5 -2
View File
@@ -72,7 +72,9 @@ def create_app() -> FastAPI:
version='1.3.0',
lifespan=lifespan,
)
instance_id = load_settings().instance_id
settings = load_settings()
instance_id = settings.instance_id
app_version = settings.app_version
def openapi():
if app.openapi_schema is None:
@@ -83,7 +85,7 @@ def create_app() -> FastAPI:
@app.middleware('http')
async def request_context(request: Request, call_next):
"""Gives every response, including unexpected failures, an X-Request-Id and X-Instance-Id."""
"""Gives every response, including unexpected failures, an X-Request-Id, X-Instance-Id and X-App-Version."""
incoming = request.headers.get('X-Request-Id')
request_id = incoming if incoming and _SAFE_REQUEST_ID.match(incoming) else str(uuid.uuid4())
request.state.request_id = request_id
@@ -94,6 +96,7 @@ def create_app() -> FastAPI:
response = _error(500, 'internal_error', _MESSAGES['internal_error'], request_id)
response.headers['X-Request-Id'] = request_id
response.headers['X-Instance-Id'] = instance_id
response.headers['X-App-Version'] = app_version
return response
@app.exception_handler(ApiError)
+4 -1
View File
@@ -10,7 +10,8 @@ from pydantic import BaseModel, ValidationError
from starlette.responses import Response
from .auth import BASIC_CHALLENGE, BEARER_CHALLENGE, parse_basic, parse_bearer
from .errors import invalid_request, not_found, unauthorized
from .drain import draining
from .errors import invalid_request, not_found, unauthorized, unavailable
from .pagination import encode_cursor, parse_page
from .schemas import CreateChat, CreateMessage, CreateUser
from .store import Chat, Store, User
@@ -80,6 +81,8 @@ async def liveness() -> JSONResponse:
@router.get('/health/ready')
async def readiness(store: Store = Depends(get_store)) -> JSONResponse:
if draining.is_set():
raise unavailable('Реплика завершает работу')
await store.ready()
return JSONResponse({'status': 'ok'})