fix(admin): bound refresh websocket workers
This commit is contained in:
1 parent
32bb5ae3d0
commit
038d1f41a5
3 files changed
+31
-4
No files matched your search
+17
-1
@@ -33,8 +33,10 @@ MAX_JSON_BODY_BYTES = 20 * 1024 * 1024
|
|||||||
MAX_UPLOAD_BYTES = 15 * 1024 * 1024
|
MAX_UPLOAD_BYTES = 15 * 1024 * 1024
|
||||||
REQUEST_READ_TIMEOUT_SECONDS = 15
|
REQUEST_READ_TIMEOUT_SECONDS = 15
|
||||||
MAX_CONCURRENT_REQUESTS = 32
|
MAX_CONCURRENT_REQUESTS = 32
|
||||||
|
MAX_CONCURRENT_ADMIN_UPDATES = 8
|
||||||
ADMIN_AUTH_WINDOW_SECONDS = 15 * 60
|
ADMIN_AUTH_WINDOW_SECONDS = 15 * 60
|
||||||
MAX_ADMIN_AUTH_ATTEMPTS = 5
|
MAX_ADMIN_AUTH_ATTEMPTS = 5
|
||||||
|
_ADMIN_UPDATE_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_ADMIN_UPDATES)
|
||||||
|
|
||||||
|
|
||||||
def detect_raster_image_type(body: bytes) -> str | None:
|
def detect_raster_image_type(body: bytes) -> str | None:
|
||||||
@@ -89,6 +91,15 @@ def clear_admin_auth_attempts(client_ip: str) -> None:
|
|||||||
_ADMIN_AUTH_ATTEMPTS.pop(client_ip, None)
|
_ADMIN_AUTH_ATTEMPTS.pop(client_ip, None)
|
||||||
|
|
||||||
|
|
||||||
|
def acquire_admin_update_slot() -> bool:
|
||||||
|
"""Reserve a bounded worker slot for a long-lived admin WebSocket."""
|
||||||
|
return _ADMIN_UPDATE_SLOTS.acquire(blocking=False)
|
||||||
|
|
||||||
|
|
||||||
|
def release_admin_update_slot() -> None:
|
||||||
|
_ADMIN_UPDATE_SLOTS.release()
|
||||||
|
|
||||||
|
|
||||||
def history_store() -> CalculationStore:
|
def history_store() -> CalculationStore:
|
||||||
global _HISTORY_STORE
|
global _HISTORY_STORE
|
||||||
if _HISTORY_STORE is None:
|
if _HISTORY_STORE is None:
|
||||||
@@ -190,14 +201,17 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if self.headers.get("Upgrade", "").lower() != "websocket" or not key:
|
if self.headers.get("Upgrade", "").lower() != "websocket" or not key:
|
||||||
self._json(400, {"error": "Требуется подключение WebSocket"})
|
self._json(400, {"error": "Требуется подключение WebSocket"})
|
||||||
return
|
return
|
||||||
|
if not acquire_admin_update_slot():
|
||||||
|
self._json(503, {"error": "Слишком много активных подключений админ-панели"})
|
||||||
|
return
|
||||||
accept = base64.b64encode(hashlib.sha1(f"{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11".encode("ascii")).digest()).decode("ascii")
|
accept = base64.b64encode(hashlib.sha1(f"{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11".encode("ascii")).digest()).decode("ascii")
|
||||||
|
try:
|
||||||
self.send_response(101, "Switching Protocols")
|
self.send_response(101, "Switching Protocols")
|
||||||
self.send_header("Upgrade", "websocket")
|
self.send_header("Upgrade", "websocket")
|
||||||
self.send_header("Connection", "Upgrade")
|
self.send_header("Connection", "Upgrade")
|
||||||
self.send_header("Sec-WebSocket-Accept", accept)
|
self.send_header("Sec-WebSocket-Accept", accept)
|
||||||
self.end_headers()
|
self.end_headers()
|
||||||
self.close_connection = True
|
self.close_connection = True
|
||||||
try:
|
|
||||||
while True:
|
while True:
|
||||||
payload = json.dumps({"type": "refresh"}, ensure_ascii=False).encode("utf-8")
|
payload = json.dumps({"type": "refresh"}, ensure_ascii=False).encode("utf-8")
|
||||||
size = len(payload)
|
size = len(payload)
|
||||||
@@ -206,6 +220,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
time.sleep(25)
|
time.sleep(25)
|
||||||
except (BrokenPipeError, ConnectionError, OSError):
|
except (BrokenPipeError, ConnectionError, OSError):
|
||||||
return
|
return
|
||||||
|
finally:
|
||||||
|
release_admin_update_slot()
|
||||||
|
|
||||||
def do_GET(self) -> None: # noqa: N802
|
def do_GET(self) -> None: # noqa: N802
|
||||||
path = urlparse(self.path).path
|
path = urlparse(self.path).path
|
||||||
|
|||||||
@@ -66,6 +66,7 @@
|
|||||||
- 2026-08-25: web calculations and applications now accept attachment URLs only when the same web process received them from the image-host upload endpoint. This prevents public JSON from planting arbitrary browser-fetchable URLs in the admin interface; the in-memory authorization is intentionally limited to the active upload-and-submit flow.
|
- 2026-08-25: web calculations and applications now accept attachment URLs only when the same web process received them from the image-host upload endpoint. This prevents public JSON from planting arbitrary browser-fetchable URLs in the admin interface; the in-memory authorization is intentionally limited to the active upload-and-submit flow.
|
||||||
- 2026-08-25: VK image mirroring checks the advertised byte length and reads at most 15 MiB plus a one-byte sentinel before uploading. Oversized upstream photos no longer allocate unbounded memory in the bot process.
|
- 2026-08-25: VK image mirroring checks the advertised byte length and reads at most 15 MiB plus a one-byte sentinel before uploading. Oversized upstream photos no longer allocate unbounded memory in the bot process.
|
||||||
- 2026-08-25: `BelkiHTTPServer` supersedes the unbounded standard threaded server. It rejects oversized declared JSON before reading, times out a slow client after 15 seconds, and serves at most 32 concurrent connections.
|
- 2026-08-25: `BelkiHTTPServer` supersedes the unbounded standard threaded server. It rejects oversized declared JSON before reading, times out a slow client after 15 seconds, and serves at most 32 concurrent connections.
|
||||||
|
- 2026-08-25: long-lived authenticated admin refresh WebSockets now have a separate eight-connection pool, so they cannot consume all 32 request workers; additional connections receive an explicit temporary-unavailable response.
|
||||||
- 2026-08-25: one-line VK/web recognition now gives explicit role labels priority over position. `сопровождающий`/`наставник`/`учитель` identify the escort, while `ученик`/`котёнок`/`бельчонок`/`подопечный` identify the ward; unlabeled pairs retain the original order-based fallback.
|
- 2026-08-25: one-line VK/web recognition now gives explicit role labels priority over position. `сопровождающий`/`наставник`/`учитель` identify the escort, while `ученик`/`котёнок`/`бельчонок`/`подопечный` identify the ward; unlabeled pairs retain the original order-based fallback.
|
||||||
- 2026-08-25: corrected Russian UX copy in the VK help and attachment flow; the web identity hint now accurately says that a manually completed pair applies only to the current calculation.
|
- 2026-08-25: corrected Russian UX copy in the VK help and attachment flow; the web identity hint now accurately says that a manually completed pair applies only to the current calculation.
|
||||||
- 2026-08-25: natural input normalizes Unicode spaces, dash variants, `ID`/`№` prefixes, spaced IDs, common date/time separators, and close role-label typos before extracting structured fields. Natasha was evaluated for Russian NER through Context7 but not added: game nicknames are better anchored by user-provided IDs and local role context than a generic person model.
|
- 2026-08-25: natural input normalizes Unicode spaces, dash variants, `ID`/`№` prefixes, spaced IDs, common date/time separators, and close role-label typos before extracting structured fields. Natasha was evaluated for Russian NER through Context7 but not added: game nicknames are better anchored by user-provided IDs and local role context than a generic person model.
|
||||||
|
|||||||
@@ -2,11 +2,11 @@ import unittest
|
|||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from app.belki.image_host import MAX_MIRRORED_IMAGE_BYTES, ImageHostClient, ImageHostError
|
from app.belki.image_host import MAX_MIRRORED_IMAGE_BYTES, ImageHostClient, ImageHostError
|
||||||
from app.main import (MAX_ADMIN_AUTH_ATTEMPTS, MAX_CONCURRENT_REQUESTS, MAX_JSON_BODY_BYTES,
|
from app.main import (MAX_ADMIN_AUTH_ATTEMPTS, MAX_CONCURRENT_ADMIN_UPDATES, MAX_CONCURRENT_REQUESTS, MAX_JSON_BODY_BYTES,
|
||||||
REQUEST_READ_TIMEOUT_SECONDS, ADMIN_AUTH_WINDOW_SECONDS, BelkiHTTPServer, Handler,
|
REQUEST_READ_TIMEOUT_SECONDS, ADMIN_AUTH_WINDOW_SECONDS, BelkiHTTPServer, Handler,
|
||||||
_ADMIN_AUTH_ATTEMPTS, _ISSUED_WEB_UPLOAD_URLS, allow_admin_auth_attempt,
|
_ADMIN_AUTH_ATTEMPTS, _ISSUED_WEB_UPLOAD_URLS, allow_admin_auth_attempt,
|
||||||
clear_admin_auth_attempts, detect_raster_image_type, safe_upload_name,
|
acquire_admin_update_slot, clear_admin_auth_attempts, detect_raster_image_type,
|
||||||
validate_web_attachments)
|
release_admin_update_slot, safe_upload_name, validate_web_attachments)
|
||||||
from app.belki.api import ApiError
|
from app.belki.api import ApiError
|
||||||
|
|
||||||
|
|
||||||
@@ -47,6 +47,16 @@ class ImageHostClientTests(unittest.TestCase):
|
|||||||
clear_admin_auth_attempts("192.0.2.1")
|
clear_admin_auth_attempts("192.0.2.1")
|
||||||
self.assertNotIn("192.0.2.1", _ADMIN_AUTH_ATTEMPTS)
|
self.assertNotIn("192.0.2.1", _ADMIN_AUTH_ATTEMPTS)
|
||||||
|
|
||||||
|
def test_admin_update_connections_have_a_separate_bounded_pool(self) -> None:
|
||||||
|
acquired = [acquire_admin_update_slot() for _ in range(MAX_CONCURRENT_ADMIN_UPDATES)]
|
||||||
|
try:
|
||||||
|
self.assertTrue(all(acquired))
|
||||||
|
self.assertFalse(acquire_admin_update_slot())
|
||||||
|
finally:
|
||||||
|
for slot in acquired:
|
||||||
|
if slot:
|
||||||
|
release_admin_update_slot()
|
||||||
|
|
||||||
def test_default_client_targets_belki_image_host(self) -> None:
|
def test_default_client_targets_belki_image_host(self) -> None:
|
||||||
with patch.dict("os.environ", {}, clear=True):
|
with patch.dict("os.environ", {}, clear=True):
|
||||||
self.assertEqual(ImageHostClient().api_url, "https://nyan.nyan404.ru")
|
self.assertEqual(ImageHostClient().api_url, "https://nyan.nyan404.ru")
|
||||||
|
|||||||
Reference in new issue
Block a user