Skip to content

Feature/heartbit endpoint#28

Merged
Fl1riX merged 3 commits into
mainfrom
feature/heartbit-endpoint
May 30, 2026
Merged

Feature/heartbit endpoint#28
Fl1riX merged 3 commits into
mainfrom
feature/heartbit-endpoint

Conversation

@Fl1riX
Copy link
Copy Markdown
Owner

@Fl1riX Fl1riX commented May 30, 2026

Summary by Sourcery

Добавить отдельную конечную точку для проверки состояния сервиса и интегрировать её в конфигурацию проверки работоспособности.

Новые возможности:

  • Ввести HTTP-эндпоинт /health, который возвращает простой статус OK для проверок «живости» (liveness checks).

Улучшения:

  • Обновить проверку состояния контейнера приложения (healthcheck), чтобы использовать новый эндпоинт /health вместо URL документации.
  • Обеспечить автоматический перезапуск контейнера Postgres, если он не был явно остановлен.
  • Настроить watchtower на очистку старых образов после обновлений.
Original summary in English

Summary by Sourcery

Add a dedicated health check endpoint and integrate it into the service health configuration.

New Features:

  • Introduce a /health HTTP endpoint that returns a simple OK status for liveness checks.

Enhancements:

  • Update the application container healthcheck to use the new /health endpoint instead of the docs URL.
  • Ensure the Postgres container restarts automatically unless explicitly stopped.
  • Configure watchtower to clean up old images after updates.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 30, 2026

Руководство для ревьюера (свернуто для небольших PR)

Руководство для ревьюера

Добавляет отдельный эндпоинт /health для проверки работоспособности приложения и обновляет Docker‑конфигурацию для его использования и улучшения поведения контейнеров.

Диаграмма последовательности для Docker health check с использованием нового эндпоинта /health

sequenceDiagram
    participant Docker
    participant App

    Docker->>App: GET /health
    App->>App: health_checker(request)
    App-->>Docker: {status: ok}
Loading

Изменения на уровне файлов

Change Details Files
Ввести легковесный эндпоинт /health и подключить к нему проверку состояния сервиса вместо /docs.
  • Добавить новый маршрут FastAPI /health, который возвращает простой JSON‑ответ со статусом и ограничен частотой до 5 запросов в минуту.
  • Обновить проверку работоспособности контейнера приложения в docker-compose, чтобы он опрашивал http://localhost:8000/health вместо эндпоинта /docs.
main.py
docker-compose.yml
Настроить поведение сервисов в Docker Compose для повышения надежности и очистки.
  • Настроить контейнер Postgres на автоматический перезапуск, если он не был явно остановлен.
  • Обновить команду контейнера watchtower, добавив флаг --cleanup, чтобы удалять устаревшие образы при сохранении текущего интервала в 300 секунд.
docker-compose.yml

Подсказки и команды

Взаимодействие с Sourcery

  • Запустить новое ревью: Оставьте комментарий @sourcery-ai review в pull request.
  • Продолжить обсуждение: Отвечайте напрямую на комментарии ревью от Sourcery.
  • Создать GitHub‑issue из комментария ревью: Попросите Sourcery создать
    issue из комментария ревью, ответив на него. Вы также можете ответить на
    комментарий ревью с @sourcery-ai issue, чтобы создать issue из этого комментария.
  • Сгенерировать заголовок pull request: Напишите @sourcery-ai в любом месте
    заголовка pull request, чтобы сгенерировать заголовок в любой момент. Также можно
    оставить комментарий @sourcery-ai title в pull request, чтобы (повторно) сгенерировать заголовок в любой момент.
  • Сгенерировать описание pull request: Напишите @sourcery-ai summary в любом месте
    тела pull request, чтобы сгенерировать описание PR в нужном месте в любой момент.
    Также можно оставить комментарий @sourcery-ai summary в pull request, чтобы
    (повторно) сгенерировать описание в любой момент.
  • Сгенерировать руководство для ревьюера: Оставьте комментарий
    @sourcery-ai guide в pull request, чтобы (повторно) сгенерировать руководство
    для ревьюера в любой момент.
  • Закрыть все комментарии Sourcery: Оставьте комментарий @sourcery-ai resolve
    в pull request, чтобы пометить все комментарии Sourcery как решенные. Полезно,
    если вы уже учли все замечания и больше не хотите их видеть.
  • Отклонить все ревью Sourcery: Оставьте комментарий @sourcery-ai dismiss
    в pull request, чтобы отклонить все текущие ревью Sourcery. Особенно полезно,
    если вы хотите начать с нуля новое ревью — не забудьте затем оставить комментарий
    @sourcery-ai review, чтобы запустить новое ревью!

Настройка работы

Зайдите в свою панель управления, чтобы:

  • Включить или отключить функции ревью, такие как автоматически сгенерированное
    Sourcery описание pull request, руководство для ревьюера и другие.
  • Изменить язык ревью.
  • Добавить, удалить или отредактировать собственные инструкции для ревью.
  • Настроить другие параметры ревью.

Получение помощи

Original review guide in English
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adds a dedicated /health endpoint for application health checks and updates Docker-related configuration to use it and improve container behavior.

Sequence diagram for Docker health check using the new /health endpoint

sequenceDiagram
    participant Docker
    participant App

    Docker->>App: GET /health
    App->>App: health_checker(request)
    App-->>Docker: {status: ok}
Loading

File-Level Changes

Change Details Files
Introduce a lightweight /health endpoint and wire service health check to use it instead of /docs.
  • Add a new FastAPI route /health that returns a simple JSON status payload and is rate-limited to 5 requests per minute.
  • Update the application container healthcheck in docker-compose to probe http://localhost:8000/health instead of the /docs endpoint.
main.py
docker-compose.yml
Adjust Docker Compose service behaviors for reliability and cleanup.
  • Configure the Postgres container to automatically restart unless explicitly stopped.
  • Update the watchtower container command to include --cleanup so obsolete images are removed while retaining the existing 300-second interval.
docker-compose.yml

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

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey — я нашёл одну проблему и оставил несколько общих замечаний:

  • Эндпоинт /health ограничен по частоте до 5/minutes, в то время как Docker healthcheck запускается каждые 10 секунд с повторами, что легко может превысить лимит и привести к ложным состояниям «unhealthy». Подумайте о том, чтобы убрать лимитер для этого эндпоинта или ослабить лимит, приведя его в соответствие с частотой healthcheck.
  • Поскольку /health предназначен только для проверки «живости» контейнера, возможно, стоит убедиться, что он остаётся максимально лёгким (без лишнего middleware или тяжёлых зависимостей) и всегда явно возвращает статус 200 OK для более понятной интеграции с оркестраторами.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `/health` endpoint is rate-limited to `5/minutes` while the Docker healthcheck runs every 10 seconds with retries, which can easily exceed the limit and cause false unhealthy states; consider removing the limiter for this endpoint or loosening the limit to align with the healthcheck frequency.
- Since `/health` is intended only for a container liveness check, you might want to ensure it stays as lightweight as possible (no extra middleware or heavy dependencies) and returns an explicit 200 OK status for clearer integration with orchestration tools.

## Individual Comments

### Comment 1
<location path="main.py" line_range="65-66" />
<code_context>
     }
+    
+@app.get("/health")
+@limiter.limit("5/minutes")
+def health_checker(request: Request):
+    return {"status": "ok"}

</code_context>
<issue_to_address>
**issue (bug_risk):** Rate limiting the `/health` endpoint conflicts with the healthcheck frequency and can mark the container unhealthy.

The Docker healthcheck runs every 10 seconds (up to 6 calls/min), but this endpoint is limited to `5/minutes`. After the limit is hit, healthchecks will get 429s and may mark the container unhealthy. For health probes, consider removing the limit or using a much higher/independent limit so operational checks are never throttled.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Помоги мне стать полезнее! Поставь, пожалуйста, 👍 или 👎 на каждом комментарии — я использую этот фидбек, чтобы улучшать обзоры.
Original comment in English

Hey - I've found 1 issue, and left some high level feedback:

  • The /health endpoint is rate-limited to 5/minutes while the Docker healthcheck runs every 10 seconds with retries, which can easily exceed the limit and cause false unhealthy states; consider removing the limiter for this endpoint or loosening the limit to align with the healthcheck frequency.
  • Since /health is intended only for a container liveness check, you might want to ensure it stays as lightweight as possible (no extra middleware or heavy dependencies) and returns an explicit 200 OK status for clearer integration with orchestration tools.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `/health` endpoint is rate-limited to `5/minutes` while the Docker healthcheck runs every 10 seconds with retries, which can easily exceed the limit and cause false unhealthy states; consider removing the limiter for this endpoint or loosening the limit to align with the healthcheck frequency.
- Since `/health` is intended only for a container liveness check, you might want to ensure it stays as lightweight as possible (no extra middleware or heavy dependencies) and returns an explicit 200 OK status for clearer integration with orchestration tools.

## Individual Comments

### Comment 1
<location path="main.py" line_range="65-66" />
<code_context>
     }
+    
+@app.get("/health")
+@limiter.limit("5/minutes")
+def health_checker(request: Request):
+    return {"status": "ok"}

</code_context>
<issue_to_address>
**issue (bug_risk):** Rate limiting the `/health` endpoint conflicts with the healthcheck frequency and can mark the container unhealthy.

The Docker healthcheck runs every 10 seconds (up to 6 calls/min), but this endpoint is limited to `5/minutes`. After the limit is hit, healthchecks will get 429s and may mark the container unhealthy. For health probes, consider removing the limit or using a much higher/independent limit so operational checks are never throttled.
</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 main.py
@coveralls
Copy link
Copy Markdown

coveralls commented May 30, 2026

Coverage Report for CI Build 26686320878

Coverage remained the same at 27.887%

Details

  • Coverage remained the same as the base build.
  • Patch coverage: No coverable lines changed in this PR.
  • No coverage regressions found.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 1169
Covered Lines: 326
Line Coverage: 27.89%
Coverage Strength: 0.56 hits per line

💛 - Coveralls

@Fl1riX Fl1riX merged commit 27e4789 into main May 30, 2026
4 checks passed
@Fl1riX Fl1riX deleted the feature/heartbit-endpoint branch May 30, 2026 14:31
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.

2 participants