Skip to content

feat: implement health check server with Docker support - #105

Merged
AshokShau merged 7 commits into
masterfrom
dev
Sep 3, 2025
Merged

AshokShau merged 7 commits into
masterfrom
dev

Conversation

@AshokShau

@AshokShau AshokShau commented Sep 1, 2025

Copy link
Copy Markdown
Owner

Summary by Sourcery

Add an HTTP health check server to the bot, integrate it into its lifecycle, and enable Docker healthcheck support.

New Features:

  • Introduce a HealthCheck service exposing '/' and '/health' endpoints for runtime status and uptime.
  • Add a Dockerfile HEALTHCHECK instruction to validate service availability via HTTP.

Enhancements:

  • Integrate the HealthCheck server startup and shutdown into the Bot initialization and teardown.
  • Expose PORT configuration for the health check server.
  • Remove the legacy watch_dog and restart logic in favor of the new HealthCheck mechanism.

@sourcery-ai

sourcery-ai Bot commented Sep 1, 2025

Copy link
Copy Markdown

Reviewer's Guide

This 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 flow

sequenceDiagram
    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)
Loading

Class diagram for new HealthCheck integration

classDiagram
    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
Loading

File-Level Changes

Change Details Files
Integrate HTTP health check server
  • Implement HealthCheck class with '/' and '/health' routes
  • Inject HealthCheck into Bot initialization and lifecycle (start/stop)
  • Expose PORT configuration for health server
  • Register HealthCheck in core package exports
TgMusic/__init__.py
TgMusic/core/_health.py
TgMusic/core/__init__.py
TgMusic/core/_config.py
Remove watchdog-based self-restart feature
  • Delete watch_dog and _restart methods from Bot
  • Remove creation of watchdog task on startup
TgMusic/__init__.py
Add Docker health check support
  • Install wget in Docker image
  • Add HEALTHCHECK directive calling the /health endpoint
Dockerfile
Refine tgcalls health_check logic
  • Comment out send_message call during client health checks
TgMusic/core/_tgcalls.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread TgMusic/__init__.py
Comment thread TgMusic/core/_health.py Outdated
Comment thread TgMusic/core/_health.py
Comment thread Dockerfile Outdated
Comment thread TgMusic/core/_health.py
@AshokShau
AshokShau merged commit 4dcfc4b into master Sep 3, 2025
1 check passed
@AshokShau
AshokShau deleted the dev branch September 3, 2025 19:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant