Оптимизировать код WebSocket сервера web/server.py#8
Merged
andchir merged 3 commits intoandchir:mainfrom Feb 6, 2026
Merged
Conversation
Adding CLAUDE.md with task information for AI processing. This file will be removed when the task is complete. Issue: andchir#7
- Add O(1) reverse lookup (WS_TO_KEY) for disconnect cleanup instead of O(n) linear scan through CONNECTIONS dict - Extract connection management into helper functions (_add_connection, _remove_connection_by_key, _remove_connection_by_ws) for consistent dual-map maintenance - Extract message parsing into _parse_message for clarity and testability - Fix ping_timeout (30s) to be less than ping_interval (60s), preventing overlapping ping/timeout cycles per websockets library recommendations - Use dict.get() and dict.pop() instead of `in` + `del` to avoid potential race conditions and redundant lookups - Remove unused `import os` - Add comprehensive unit tests (23 tests) covering message parsing, connection lifecycle, and the register handler Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This reverts commit 8c79270.
Contributor
Author
🤖 Solution Draft LogThis log file contains the complete execution trace of the AI solution draft process. 💰 Cost estimation:
Now working session is ended, feel free to review and add any feedback on the solution draft. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
📋 Описание изменений / Changes Description
Этот PR решает issue #7 — оптимизация кода WebSocket сервера
web/server.py.This PR solves issue #7 — optimization of the WebSocket server code
web/server.py.✅ Реализованные оптимизации / Implemented Optimizations
O(1) очистка при отключении вместо O(n) линейного поиска
WS_TO_KEY(websocket id → key) для мгновенного поиска ключа при отключении клиентаfor key, con in CONNECTIONS.items()) по всем соединениям — O(n) на каждое отключение_remove_connection_by_ws()с O(1) обратным поиском черезWS_TO_KEYВынесение управления соединениями в вспомогательные функции
_add_connection()— регистрация с поддержкой обоих маппингов_remove_connection_by_key()— удаление по ключу из обоих маппингов_remove_connection_by_ws()— удаление по websocket с O(1) обратным поискомВынесение парсинга сообщений в
_parse_message()Исправлен
ping_timeout(30с вместо 90с)ping_timeout=90>ping_interval=60, что означало наложение циклов ping/timeoutping_timeout=30<ping_interval=60, как рекомендуется документацией websocketsИспользование
dict.get()/dict.pop()вместоin+delУдалён неиспользуемый
import os🧪 Тестирование / Testing
Добавлено 23 юнит-теста в
tests/test_ws_server.py:TestWebSocketMessage— тесты dataclass WebSocketMessageTestParseMessage— тесты парсинга сообщений (JSON, plain text, невалидный JSON)TestConnectionManagement— тесты добавления/удаления соединений, UUID переназначения, O(1) обратного поискаTestRegisterHandler— тесты async handler register (приветствие, подключение, пересылка, ошибки)TestPingTimeout— верификация ping_timeout < ping_intervalВсе 25 тестов проходят (23 новых + 2 существующих верификационных).
Fixes #7
🤖 Generated with Claude Code