Skip to content

feat(deploy): Add a deployment script to the server and a configurati…#37

Merged
Fl1riX merged 1 commit into
mainfrom
feature/webhook-deploy
Jun 3, 2026
Merged

feat(deploy): Add a deployment script to the server and a configurati…#37
Fl1riX merged 1 commit into
mainfrom
feature/webhook-deploy

Conversation

@Fl1riX

@Fl1riX Fl1riX commented Jun 3, 2026

Copy link
Copy Markdown
Owner

…on file for the webhook

Summary by Sourcery

Добавить автоматизацию серверного деплоя, запускаемую через вебхук, и внести небольшое изменение в контекст сессии базы данных.

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

  • Ввести конфигурацию вебхука для запуска деплоя через HTTP-эндпоинт.
  • Добавить shell-скрипт деплоя, который подтягивает последний код и перезапускает Docker-сервисы.

Улучшения:

  • Аннотировать асинхронный контекст сессии базы данных в задаче очистки «magic token», чтобы удовлетворить требования инструментов проверки типов.
Original summary in English

Summary by Sourcery

Add server-side deployment automation triggered via webhook and make a minor adjustment to a database session context.

New Features:

  • Introduce a webhook hook configuration for triggering deployments via an HTTP endpoint.
  • Add a deployment shell script that pulls the latest code and restarts Docker services.

Enhancements:

  • Annotate the async database session context in the magic token cleanup task to satisfy type checking tools.

@sourcery-ai

sourcery-ai Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Руководство для рецензента

Добавляет простой конвейер деплоя с использованием shell-скрипта, вызываемого вебхуком, и немного изменяет контекст сессии базы данных в задаче очистки magic-токенов, чтобы обойти проблемы с проверкой типов.

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

Изменение Подробности Файлы
Введение конфигурации вебхука для запуска деплоя на сервере.
  • Добавить конфигурацию hooks.yaml, описывающую идентификатор endpoint’а вебхука деплоя и путь к командe выполнения
  • Настроить рабочую директорию для команд деплоя и определить HMAC-SHA256-проверку полезной нагрузки с общим секретом, считываемым из заголовков
  • Задокументировать, как сгенерировать секрет вебхука и где разместить конфигурационный файл на сервере
deploy/hooks.yaml
Добавить shell-скрипт деплоя, который подтягивает последний код и переразворачивает контейнеры.
  • Создать скрипт deploy.sh, который переходит в директорию проекта и подтягивает последние изменения из ветки main
  • Обновляет образы docker и перезапускает контейнеры в фоновом режиме с использованием docker compose
  • Включает строгую обработку ошибок bash через set -e для мгновенного падения при ошибках
deploy/deploy.sh
Обход проблемы проверки типов в асинхронном контекстном менеджере DB-сессии в задаче очистки magic-токенов.
  • Добавить комментарий type: ignore к асинхронному контекстному менеджеру SessionLocal, используемому для очистки просроченных токенов, чтобы подавить предупреждения проверяющего типы
src/infrastructure/tasks/cleanup_magic_tokens.py

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

Взаимодействие с 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

Adds a simple deployment pipeline using a webhook-configured shell script and slightly adjusts a database session context in the magic token cleanup task to bypass type checking issues.

File-Level Changes

Change Details Files
Introduce a webhook configuration for triggering deployments on the server.
  • Add a hooks.yaml configuration describing a deploy webhook endpoint id and execution command path
  • Configure working directory for deployment commands and define HMAC-SHA256 payload validation with a shared secret read from headers
  • Document how to generate the webhook secret and where to place the configuration file on the server
deploy/hooks.yaml
Add a deployment shell script that pulls the latest code and redeploys containers.
  • Create deploy.sh script that changes into the project directory and pulls latest changes from the main branch
  • Update docker images and restart containers in detached mode using docker compose
  • Enable strict bash error handling via set -e to fail fast on errors
deploy/deploy.sh
Work around a type-checking issue in the async DB session context manager in the magic token cleanup task.
  • Append a type: ignore comment to the async SessionLocal context manager used for cleaning up expired tokens to suppress type checker warnings
src/infrastructure/tasks/cleanup_magic_tokens.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

@Fl1riX Fl1riX merged commit 9fda4b2 into main Jun 3, 2026
4 checks passed

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - я нашёл одну проблему и оставил немного общих комментариев:

  • # type: ignore на SessionLocal() указывает на несоответствие типов; вместо того чтобы полностью отключать проверку типов в этом месте, попробуйте скорректировать тип аннотации SessionLocal или использовать более точное приведение типов, чтобы mypy мог корректно проверить это использование.
  • В deploy/hooks.yaml ключ parametr, похоже, написан с ошибкой и, скорее всего, будет проигнорирован сервисом вебхуков; перепроверьте ожидаемый формат конфигурации (например, parameter или rules), чтобы заголовок HMAC действительно был прочитан.
  • Скрипт деплоя и конфиг вебхука используют жёстко прописанные абсолютные пути и конкретный пользовательский каталог (/home/fl1rix/SteelTime), что усложняет повторное использование и изменение окружения; рассмотрите возможность параметризовать корень проекта через переменные окружения или одно конфигурационное значение.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `# type: ignore` on `SessionLocal()` suggests a typing mismatch; instead of suppressing all type checking here, consider adjusting the `SessionLocal` type annotation or using a more precise cast so mypy can validate this usage.
- In `deploy/hooks.yaml`, the `parametr` key appears to be misspelled and will likely be ignored by the webhook service; double-check the expected configuration format (e.g., `parameter` or `rules`) so the HMAC header is actually read.
- The deployment script and webhook config hardcode absolute paths and a specific user directory (`/home/fl1rix/SteelTime`), which makes reuse and environment changes difficult; consider parameterizing the project root via environment variables or a single config value instead.

## Individual Comments

### Comment 1
<location path="deploy/hooks.yaml" line_range="8" />
<code_context>
+    match:
+      type: payload-hmac-sha256
+      secret: "ЗАМЕНИТЬ НА РЕАЛЬНЫЙ"
+      parametr:
+        source: header
+        name: X-Hub-Signature-256
</code_context>
<issue_to_address>
**issue (bug_risk):** Check the `parametr` key spelling against the webhook config schema.

In most webhook configs this key is named `parameter` (or another defined field), not `parametr`. With the wrong key name the rule may be ignored. Please verify the correct key in your webhook service’s config schema.
</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 # type: ignore on SessionLocal() suggests a typing mismatch; instead of suppressing all type checking here, consider adjusting the SessionLocal type annotation or using a more precise cast so mypy can validate this usage.
  • In deploy/hooks.yaml, the parametr key appears to be misspelled and will likely be ignored by the webhook service; double-check the expected configuration format (e.g., parameter or rules) so the HMAC header is actually read.
  • The deployment script and webhook config hardcode absolute paths and a specific user directory (/home/fl1rix/SteelTime), which makes reuse and environment changes difficult; consider parameterizing the project root via environment variables or a single config value instead.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `# type: ignore` on `SessionLocal()` suggests a typing mismatch; instead of suppressing all type checking here, consider adjusting the `SessionLocal` type annotation or using a more precise cast so mypy can validate this usage.
- In `deploy/hooks.yaml`, the `parametr` key appears to be misspelled and will likely be ignored by the webhook service; double-check the expected configuration format (e.g., `parameter` or `rules`) so the HMAC header is actually read.
- The deployment script and webhook config hardcode absolute paths and a specific user directory (`/home/fl1rix/SteelTime`), which makes reuse and environment changes difficult; consider parameterizing the project root via environment variables or a single config value instead.

## Individual Comments

### Comment 1
<location path="deploy/hooks.yaml" line_range="8" />
<code_context>
+    match:
+      type: payload-hmac-sha256
+      secret: "ЗАМЕНИТЬ НА РЕАЛЬНЫЙ"
+      parametr:
+        source: header
+        name: X-Hub-Signature-256
</code_context>
<issue_to_address>
**issue (bug_risk):** Check the `parametr` key spelling against the webhook config schema.

In most webhook configs this key is named `parameter` (or another defined field), not `parametr`. With the wrong key name the rule may be ignored. Please verify the correct key in your webhook service’s config schema.
</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 deploy/hooks.yaml
match:
type: payload-hmac-sha256
secret: "ЗАМЕНИТЬ НА РЕАЛЬНЫЙ"
parametr:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): Проверьте написание ключа parametr в соответствии со схемой конфигурации вебхука.

В большинстве конфигураций вебхуков этот ключ называется parameter (или другим заранее определённым полем), а не parametr. При неверном названии ключа правило может быть проигнорировано. Пожалуйста, уточните корректное имя ключа в схеме конфигурации вашего сервиса вебхуков.

Original comment in English

issue (bug_risk): Check the parametr key spelling against the webhook config schema.

In most webhook configs this key is named parameter (or another defined field), not parametr. With the wrong key name the rule may be ignored. Please verify the correct key in your webhook service’s config schema.

@github-actions

github-actions Bot commented Jun 3, 2026

Copy link
Copy Markdown

Coverage Report for CI Build 26872096363

Coverage remained the same at 30.313%

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: 1214
Covered Lines: 368
Line Coverage: 30.31%
Coverage Strength: 0.61 hits per line

💛 - Coveralls

1 similar comment
@github-actions

github-actions Bot commented Jun 3, 2026

Copy link
Copy Markdown

Coverage Report for CI Build 26872096363

Coverage remained the same at 30.313%

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: 1214
Covered Lines: 368
Line Coverage: 30.31%
Coverage Strength: 0.61 hits per line

💛 - Coveralls

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