Conversation
Reviewer's GuideThis PR adds an aiohttp-based health check server module into the Bot lifecycle, removes the legacy watchdog restart mechanism, and enhances the Docker setup with wget installation and a HEALTHCHECK directive pointing to the new /health endpoint. Sequence diagram for health check HTTP request flowsequenceDiagram
participant Docker
participant HealthCheckServer
participant Bot
participant PyrogramCall
Docker->>HealthCheckServer: HTTP GET /health
HealthCheckServer->>Bot: Check is_running
HealthCheckServer->>PyrogramCall: health_check()
PyrogramCall-->>HealthCheckServer: status
HealthCheckServer-->>Docker: JSON response (healthy/status)
Class diagram for new HealthCheck integrationclassDiagram
class Bot {
+HealthCheck health_check
+async _initialize_components()
+async stop(graceful)
}
class HealthCheck {
+__init__(client, port, host)
+async start()
+async stop()
+async home(request)
+async health_check(request)
-client
-port
-host
-app
-runner
-site
}
Bot --> HealthCheck : uses
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey there - I've reviewed your changes and they look great!
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location> `TgMusic/__init__.py:83` </location>
<code_context>
await self.call.register_decorators()
await super().start()
await self.call_manager.start()
+ await self.health_check.start()
self.logger.info("Bot started successfully")
</code_context>
<issue_to_address>
HealthCheck server startup should be robust to port binding errors.
Currently, if health_check.start() fails due to a port issue, the bot will not start. Please handle exceptions here and log errors, or implement a retry mechanism if feasible.
</issue_to_address>
<suggested_fix>
<<<<<<< SEARCH
await self.call.register_decorators()
await super().start()
await self.call_manager.start()
await self.health_check.start()
self.logger.info("Bot started successfully")
=======
await self.call.register_decorators()
await super().start()
await self.call_manager.start()
try:
await self.health_check.start()
except Exception as e:
self.logger.error(f"HealthCheck server failed to start: {e}", exc_info=True)
self.logger.info("Bot started successfully")
>>>>>>> REPLACE
</suggested_fix>
### Comment 2
<location> `TgMusic/core/_health.py:26` </location>
<code_context>
+ })
+
+ async def health_check(self, _: web.Request):
+ if not self.client:
+ raise web.HTTPServiceUnavailable(text="Client not initialized")
+
+ if not getattr(self.client, 'is_running', False):
+ raise web.HTTPServiceUnavailable(text="Client not running")
+
</code_context>
<issue_to_address>
HealthCheck endpoint may leak internal state via error messages.
Use generic error messages in HTTPServiceUnavailable responses and log detailed information internally to avoid exposing internal state.
</issue_to_address>
<suggested_fix>
<<<<<<< SEARCH
async def health_check(self, _: web.Request):
if not self.client:
raise web.HTTPServiceUnavailable(text="Client not initialized")
if not getattr(self.client, 'is_running', False):
raise web.HTTPServiceUnavailable(text="Client not running")
=======
async def health_check(self, _: web.Request):
import logging
if not self.client:
logging.error("HealthCheck failed: Client not initialized")
raise web.HTTPServiceUnavailable(text="Service temporarily unavailable")
if not getattr(self.client, 'is_running', False):
logging.error("HealthCheck failed: Client not running")
raise web.HTTPServiceUnavailable(text="Service temporarily unavailable")
>>>>>>> REPLACE
</suggested_fix>
### Comment 3
<location> `TgMusic/core/_health.py:42` </location>
<code_context>
+ 'status': 'healthy',
+ 'version': getattr(self.client, '_version', 'unknown'),
+ 'uptime': getattr(self.client, '_get_uptime', lambda: 0)(),
+ 'timestamp': asyncio.get_event_loop().time(),
+ })
+
</code_context>
<issue_to_address>
Consider using a monotonic or UTC timestamp for health endpoint.
asyncio.get_event_loop().time() provides a monotonic value, which is not suitable for external timestamps. Use time.time() or datetime.utcnow().isoformat() for a standard, externally meaningful timestamp.
Suggested implementation:
```python
return web.json_response({
'status': 'healthy',
'version': getattr(self.client, '_version', 'unknown'),
'uptime': getattr(self.client, '_get_uptime', lambda: 0)(),
'timestamp': datetime.datetime.utcnow().isoformat(),
})
```
```python
import datetime
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from TgMusic import Bot
```
</issue_to_address>
### Comment 4
<location> `Dockerfile:17` </location>
<code_context>
RUN uv pip install -e . --system
+# Health check configuration
+HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
+ CMD wget --no-verbose --tries=1 --spider http://localhost:5068/health || exit 1
+
</code_context>
<issue_to_address>
Healthcheck endpoint is hardcoded to port 5068.
If the port is configurable, use Docker ARG or ENV to set the healthcheck port dynamically.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
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.
Summary by Sourcery
Add an HTTP health check server to the bot, integrate it into its lifecycle, and enable Docker healthcheck support.
New Features:
Enhancements: