[WIP] Fix WebSocket server close handling for graceful shutdown#51
Closed
[WIP] Fix WebSocket server close handling for graceful shutdown#51
Conversation
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.
Thanks for asking me to work on this. I will get started on it and keep this PR's description up to date as I form a plan and make progress.
Original prompt
Problem Statement: Graceful WebSocket Shutdown without Client Hang
Current Issue
The WebSocket server's
Close()method ininternal/websocket/server.go(lines 519-533) doesn't have proper timeout handling for gracefully shutting down WebSocket connections. This can cause:Current Implementation (Problematic)
Problems:
Solution Requirements
Add Graceful Shutdown Method:
Shutdown(ctx context.Context)with configurable timeoutModify Server API Structure:
Update API Server Integration (
internal/api/server.go):Add Unit Tests:
Add Integration Example:
Expected Behavior After Fix
Files to Modify
internal/websocket/server.go- Add graceful shutdown with timeoutinternal/websocket/client.go- Add close notification flaginternal/api/server.go- Integrate WebSocket shutdown into API server shutdowninternal/websocket/server_test.go- Add comprehensive shutdown testscmd/api/main.goor equivalent - Document shutdown sequenceTesting Approach
The following is the prior conversation context from the user's chat exploration (may be truncated):
User: Проанализируй репозиторий и найди плохие моменты по типу варианты для оптимизации и тд
Assistant: Я проанализирую репозиторий godofphonk/ServerEyeAPI. Начну с получения информации о его структуре и содержимом.
Assistant: Отлично! Теперь давайте подробнее изучим основные файлы проекта:
Assistant: Теперь получу более детальную информацию о коде:
Assistant: Let me search for more specific issues:
Assistant: Отлично! Я проанализировал репозиторий ServerEyeAPI. Вот подробный отчет о найденных проблемах и возможностях оптимизации:
🚨 Критические проблемы и "плохие моменты"
1. Отключенная аутентификация API (🔓 Уязвимость безопасности)
Файл:
internal/api/server.go, строка 140Проблема: Middleware для проверки API ключей закомментирована, что означает, что все защищенные эндпоинты не защищены.
Риск: Любой может получить доступ к confidential данным.
Решение: Активировать middleware и применить его к защищенным маршрутам.
2. CORS открыт для всех (⚠️ Security)
Файл:
internal/api/middleware/cors.goПроблема: CORS позволяет запросам с любых источников, что опасно для API.
Решение: Ограничить
Access-Control-Allow-Originизвестными доменами из конфигурации.3. Неправильное преобразование server_key → server_id
Файл:
internal/handlers/static_info.go, множественные места