docs: document HTTP server helpers
This commit is contained in:
1 parent
e4fa5c7ab9
commit
df4b864d1d
1 file changed
+16
+16
@@ -111,6 +111,7 @@ def allow_admin_auth_attempt(client_ip: str, *, now: float | None = None) -> boo
|
|||||||
|
|
||||||
|
|
||||||
def clear_admin_auth_attempts(client_ip: str) -> None:
|
def clear_admin_auth_attempts(client_ip: str) -> None:
|
||||||
|
"""Удаляет временные неудачные попытки входа администратора для IP."""
|
||||||
with _ADMIN_AUTH_LOCK:
|
with _ADMIN_AUTH_LOCK:
|
||||||
_ADMIN_AUTH_ATTEMPTS.pop(client_ip, None)
|
_ADMIN_AUTH_ATTEMPTS.pop(client_ip, None)
|
||||||
|
|
||||||
@@ -129,6 +130,7 @@ def remember_admin_session(token: str, *, now: float | None = None) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def admin_session_authorized(token: str, *, now: float | None = None) -> bool:
|
def admin_session_authorized(token: str, *, now: float | None = None) -> bool:
|
||||||
|
"""Проверяет токен сессии и удаляет его после истечения срока действия."""
|
||||||
timestamp = time.monotonic() if now is None else now
|
timestamp = time.monotonic() if now is None else now
|
||||||
with _ADMIN_SESSIONS_LOCK:
|
with _ADMIN_SESSIONS_LOCK:
|
||||||
expiry = _ADMIN_SESSIONS.get(token)
|
expiry = _ADMIN_SESSIONS.get(token)
|
||||||
@@ -141,6 +143,7 @@ def admin_session_authorized(token: str, *, now: float | None = None) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def forget_admin_session(token: str) -> None:
|
def forget_admin_session(token: str) -> None:
|
||||||
|
"""Удаляет токен административной сессии из памяти процесса."""
|
||||||
with _ADMIN_SESSIONS_LOCK:
|
with _ADMIN_SESSIONS_LOCK:
|
||||||
_ADMIN_SESSIONS.pop(token, None)
|
_ADMIN_SESSIONS.pop(token, None)
|
||||||
|
|
||||||
@@ -151,10 +154,12 @@ def acquire_admin_update_slot() -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def release_admin_update_slot() -> None:
|
def release_admin_update_slot() -> None:
|
||||||
|
"""Освобождает глобальный слот фонового обновления заявок."""
|
||||||
_ADMIN_UPDATE_SLOTS.release()
|
_ADMIN_UPDATE_SLOTS.release()
|
||||||
|
|
||||||
|
|
||||||
def history_store() -> CalculationStore:
|
def history_store() -> CalculationStore:
|
||||||
|
"""Лениво создаёт singleton хранилища истории расчётов."""
|
||||||
global _HISTORY_STORE
|
global _HISTORY_STORE
|
||||||
if _HISTORY_STORE is None:
|
if _HISTORY_STORE is None:
|
||||||
_HISTORY_STORE = CalculationStore.from_environment()
|
_HISTORY_STORE = CalculationStore.from_environment()
|
||||||
@@ -162,6 +167,7 @@ def history_store() -> CalculationStore:
|
|||||||
|
|
||||||
|
|
||||||
def identity_dir() -> IdentityDirectory:
|
def identity_dir() -> IdentityDirectory:
|
||||||
|
"""Лениво создаёт справочник персонажей из окружения."""
|
||||||
global _IDENTITY_DIR
|
global _IDENTITY_DIR
|
||||||
if _IDENTITY_DIR is None:
|
if _IDENTITY_DIR is None:
|
||||||
_IDENTITY_DIR = IdentityDirectory.from_environment(persistent=True)
|
_IDENTITY_DIR = IdentityDirectory.from_environment(persistent=True)
|
||||||
@@ -169,6 +175,7 @@ def identity_dir() -> IdentityDirectory:
|
|||||||
|
|
||||||
|
|
||||||
def application_store() -> ApplicationStore:
|
def application_store() -> ApplicationStore:
|
||||||
|
"""Лениво создаёт singleton хранилища заявок."""
|
||||||
global _APPLICATION_STORE
|
global _APPLICATION_STORE
|
||||||
if _APPLICATION_STORE is None:
|
if _APPLICATION_STORE is None:
|
||||||
_APPLICATION_STORE = ApplicationStore.from_environment()
|
_APPLICATION_STORE = ApplicationStore.from_environment()
|
||||||
@@ -184,21 +191,25 @@ class BelkiHTTPServer(ThreadingHTTPServer):
|
|||||||
"""Threaded server with bounded slow-client and worker resource use."""
|
"""Threaded server with bounded slow-client and worker resource use."""
|
||||||
|
|
||||||
def __init__(self, server_address: tuple[str, int], handler_class: type[BaseHTTPRequestHandler]) -> None:
|
def __init__(self, server_address: tuple[str, int], handler_class: type[BaseHTTPRequestHandler]) -> None:
|
||||||
|
"""Настраивает многопоточный HTTP-сервер и лимиты обработки."""
|
||||||
super().__init__(server_address, handler_class)
|
super().__init__(server_address, handler_class)
|
||||||
self._request_slots = threading.BoundedSemaphore(MAX_CONCURRENT_REQUESTS)
|
self._request_slots = threading.BoundedSemaphore(MAX_CONCURRENT_REQUESTS)
|
||||||
|
|
||||||
def get_request(self): # type: ignore[no-untyped-def]
|
def get_request(self): # type: ignore[no-untyped-def]
|
||||||
|
"""Получает клиентский сокет и применяет короткий таймаут чтения."""
|
||||||
request, client_address = super().get_request()
|
request, client_address = super().get_request()
|
||||||
request.settimeout(REQUEST_READ_TIMEOUT_SECONDS)
|
request.settimeout(REQUEST_READ_TIMEOUT_SECONDS)
|
||||||
return request, client_address
|
return request, client_address
|
||||||
|
|
||||||
def process_request(self, request, client_address) -> None: # type: ignore[no-untyped-def]
|
def process_request(self, request, client_address) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""Передаёт соединение в отдельный поток обработки."""
|
||||||
if not self._request_slots.acquire(blocking=False):
|
if not self._request_slots.acquire(blocking=False):
|
||||||
request.close()
|
request.close()
|
||||||
return
|
return
|
||||||
super().process_request(request, client_address)
|
super().process_request(request, client_address)
|
||||||
|
|
||||||
def process_request_thread(self, request, client_address) -> None: # type: ignore[no-untyped-def]
|
def process_request_thread(self, request, client_address) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""Обрабатывает соединение и закрывает сокет после завершения."""
|
||||||
try:
|
try:
|
||||||
super().process_request_thread(request, client_address)
|
super().process_request_thread(request, client_address)
|
||||||
finally:
|
finally:
|
||||||
@@ -210,6 +221,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
protocol_version = "HTTP/1.1"
|
protocol_version = "HTTP/1.1"
|
||||||
|
|
||||||
def _json(self, status: int, body: dict) -> None:
|
def _json(self, status: int, body: dict) -> None:
|
||||||
|
"""Отправляет JSON-ответ с указанным HTTP-статусом."""
|
||||||
encoded = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
encoded = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||||
self.send_response(status)
|
self.send_response(status)
|
||||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||||
@@ -218,13 +230,16 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self.wfile.write(encoded)
|
self.wfile.write(encoded)
|
||||||
|
|
||||||
def _session_token(self, name: str) -> str:
|
def _session_token(self, name: str) -> str:
|
||||||
|
"""Извлекает именованный токен из cookie текущего запроса."""
|
||||||
cookies = self.headers.get("Cookie", "")
|
cookies = self.headers.get("Cookie", "")
|
||||||
return next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith(f"{name}=")), "")
|
return next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith(f"{name}=")), "")
|
||||||
|
|
||||||
def _admin_session_authorized(self) -> bool:
|
def _admin_session_authorized(self) -> bool:
|
||||||
|
"""Проверяет авторизацию административной сессии запроса."""
|
||||||
return admin_session_authorized(self._session_token("belki_admin_session"))
|
return admin_session_authorized(self._session_token("belki_admin_session"))
|
||||||
|
|
||||||
def _admin_authorized(self) -> bool:
|
def _admin_authorized(self) -> bool:
|
||||||
|
"""Проверяет административную cookie и срок её действия."""
|
||||||
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
|
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
|
||||||
if not expected:
|
if not expected:
|
||||||
self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"})
|
self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"})
|
||||||
@@ -235,6 +250,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
def _json_with_cookie(self, status: int, body: dict, cookie: str) -> None:
|
def _json_with_cookie(self, status: int, body: dict, cookie: str) -> None:
|
||||||
|
"""Отправляет JSON-ответ и добавляет заголовок Set-Cookie."""
|
||||||
encoded = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
encoded = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||||
self.send_response(status)
|
self.send_response(status)
|
||||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||||
|
|||||||
Reference in new issue
Block a user